Shoulda 2.10: time for a little love for ActionController

Joe Ferris


Shoulda’s ActiveRecord macros received some well-deserved attention in 2.9.0, but what’s Shoulda without a little extra sugar for your controller tests?

RSpec ActionController matchers

Shoulda’s much-loved ActiveRecord macros have been available to RSpec users for a little while now, but RSpec controller specs have had little love from Shoulda so far. Shoulda 2.10 ends this streak of injustice, so RSpec users can now respond_with and route and set_the_flash until the cows come home. Behold!

describe UsersController, "routes" do
  it { should route(:get, '/users/1').
                to(:action => 'show', :id => '1') }

describe UsersController, "on GET to show with a valid id" do
  subject { controller }

  before(:each) do
    get :show, :id => User.first.to_param

  it { should assign_to(:user) }
  it { should respond_with(:success) }
  it { should not_set_the_flash) }

The upcoming RSpec 1.2 release will implicitly set the subject for controller specs, so that subject line will no longer be necessary after that release.

For more examples of RSpec matchers, see the Shoulda docs

Block arguments

Several Shoulda macros expected strings that were evaluated as Ruby. Shoulda now accepts a block argument for each of these macros, allowing you to keep your Ruby in Ruby:

# before
should_assign_to(:user, '@user')
should_return_from_session(:user_id, '')

# after
should_assign_to(:user) { @user }
should_redirect_to("the user's profile") { user_url(@user) }
should_set_session(:user_id) { }

The string evals still live on for now, but you’ll receive a deprecation warning when using them. Also, it’s worth noting that the old string evals referenced instance variables from the controller, but the blocks respect instance variables from your tests.

Time to move on

In addition to deprecating string evals, some of our old, deprecated friends have been removed entirely: shouldberestful and loadallfixtures are gone for good. Fair thee well, old friends!

Well, what are you waiting for? Time to install the gems:

sudo gem install thoughtbot-shoulda -s

Visit our Open Source page to learn more about our team’s contributions.