28 August 2009 · About 3 minutes read

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:

```bash# 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:

```ruby# 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
# ...




Now you can run a Spork server instance with:

bash$ spork

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

```textPreloading 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:

```ruby# spec/spec_helper.rb


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:

```bash$ 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:

```text# spec/spec.opts


–format progress

–loadby mtime



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:

bash$ 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.

Chris Blunt
Chris Blunt@cblunt
Chris is the founder of Plymouth Software. As well as code and business, he enjoys being a Dad, swimming, and the fine art of drinking tea.