Rails: Configuring RSpec for Spork

RSpec is great for behaviour driven development in Rails. However, as the amount of code you test increases, so too does the time taken to run the tests.

To help speed things up, I've been using Spork; a small server that preloads all your library code and sits waiting for specs to run. Installing and setting up your project to use Spork is quick to do:

# Spork relies on cucumber
$ gem install cucumber spork

# Prepares your project for Spork
$ cd railsap
$ spork --bootstrap

Once your project is bootstrapped, you'll need to move all your RSpec initialisation code into the prefork block that Spork has added to your spec_helper.rb:

# spec/spec_helper.rb
require 'rubygems'
require 'spork'

Spork.prefork do
  # All the default RSpec stuff goes here, e.g:
  ENV["RAILS_ENV"] ||= 'test'
  require File.dirname(__FILE__) + "/../config/environment"
  require 'spec/autorun'
  require 'spec/rails'
  Spec::Runner.configure do |config|
    # ...
  end
end
#...

Now you can run a Spork server instance with:

$ spork

For me, though, Spork refused to run. It just kept throwing the following exception:

Preloading Rails environment
Loading Spork.prefork block...
uninitialized constant MissingSourceFile (NameError)

Fixing the configuration for Spork

For a short while, I skipped Spork and continued running my specs as normal. Eventually the number of specs I was testing took several seconds for each run, which soon added up to a lot of waiting.

So, after some searching and thanks to this post on Google Groups, I learned the exception is caused by a condition included as part of the default RSpec initialisation code.

The solution is to remove the condition from your spec_helper.rb:

# spec/spec_helper.rb
# ...
# before:
# require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
require File.dirname(__FILE__) + "/../config/environment"

Now you should be able to run Spork with:

$ spork
Using RSpec
Preloading Rails environment
Loading Spork.prefork block...
Spork is ready and listening on 8989!

Finally, you can tell RSpec to connect to and use Spork if it is running. Just add --drb to your spec.opts file:

# spec/spec.opts
--colour
--format progress
--loadby mtime
--reverse
--drb

Note that these options are only used if you run RSpec through the rake spec: tasks. If you run specs manually, remember to add the --drb option, for example:

$ script/spec --colour --drb spec/controllers/users_controller_spec.rb

Changing your spec setup code by removing the condition is obviously far from ideal, and it may break compatability with cucumber (see this lighthouse ticket for more information). However, it at least means you can take advantage of Spork until a proper fix is implemented.

« Previous Post

avatar

Chris Blunt

Plymouth Software

Devon, England

twitter.com/cblunt

github.com/cblunt

 

facebook.com/cbluntuk

flickr.com/photos/cblunt