Continuous Testing Feedback with Guard and Spork

If you do test driven development in Ruby on Rails you are probably familiar with running

$ rspec spec/whatever_spec.rb

at the command line where you’ll see green or red, depending on the phase of the testing.  Guard is a Ruby Gem that automates running your tests and monitoring filesystem changes so that when we change a _spec.rb file only those tests get run.

And it gets better when adding Spork to the process. Rspec has to reload the entire Rails environment each time it runs. The Spork Test Server solves this problem by loading the environment once, then maintaining a pool of processes for running future tests.

The very best feature of Guard is that you get continuous testing feedback after adding the Notify Gems in your Gemfile.

# Notify and Test Gems for Linux
group :test do
    .
    gem ‘rb-inotify’, ‘0.8.8’
    gem ‘libnotify’, ‘0.5.9’
end

Here’s a screenshot of Guard and Spork in action, providing RSpec Test feedback with Linux Mint Desktop Notifications at top right and all red-green details in the Terminal window bottom left.

I won’t go into all of the configuration details, but to give you an idea of the setup required to enjoy continuous TDD feedback we

1) Add the Guard Gem and the Spork dependency to our Gemfile

group :development, :test do
  .
  .
  gem ‘guard-rspec’, ‘2.5.4’
  gem ‘guard-spork’, :github => ‘guard/guard-spork’
  gem ‘spork’, ‘0.9.2’
end

2) Add the notify gems (shown earlier)

3) Initialize Guard so that it works with RSpec. 

$ bundle exec guard init rspec

This will also create our Guardfile which we’ll want to modify so that Guard doesn’t run all the tests after a failing test passes.

4) We next bootstrap the Spork configuration with

$ bundle exec spork –bootstrap

and update our spec/spec_helper.rb to add environment loading. (not shown)

5) To configure RSpec to automatically use Spork we add the –drb option to our .rspec file

6) Rather than initializing Spork with Guard with

$ bundle exec guard init spork

we’ll modify our Guardfile to initialize the Spork Server. (not shown)

At this point we can enjoy continuous testing feedback all day (and night) long!

$ guard

Yousa!