2012-01-25

Fast specs without loading Rails, with Ruby 1.9

My goal is to create a fast test suite, which does not load Rails. You can see this concept discussed by Gary Bernhardt in one of his DestroyAllSoftware screencasts here.

The gist of it is, I have a spec_fast directory, and a test like RAILS_ROOT/spec_fast/lib/foo_spec.rb.

I also have a RAILS_ROOT/spec_fast/spec_helper that e.g. defines constants that would exist if Rails were loaded, that my code might need.

The problem is that foo_spec can't require from the spec_fast directory, because it's not in $LOAD_PATH. Ruby 1.9 apparently doesn't add "." to $LOAD_PATH.

I tried to hack Gary's fast test script to prepend it to $LOAD_PATH by adding a few things.
if [ $need_rails ]; then
    command="ruby -S bundle exec $command"
else
    this_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    rails_dir=$(dirname $this_dir)
    spec_fast_dir="$rails_dir/spec_fast"
    command="RUBYLIB=\"$spec_fast_dir\" $command"
fi
But then I get a complaint: script/spec_fast: line 39: RUBYLIB="/Users/USER/workspace/RAILS_ROOT/spec_fast": No such file or directory Clearly I'm lacking some BaSH expertise, although maybe there's a better way to solve this problem anyway?

UPDATE

This seems to work.
command="rspec $filename"

if [ $need_rails ]; then
    RAILS_ENV=test ruby -S bundle exec $rspec_exec
else
    this_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    rails_dir=$(dirname $this_dir)
    spec_fast_dir="$rails_dir/spec_fast"
    RUBYLIB="$spec_fast_dir" $command $filename
fi
And then I just use "require 'fast_spec_helper'" in my fast spec.

No comments: