Shoulda Gets Busy with Your Controllers

Tammer Saleh

A while back we released the Shoulda Plugin to help with testing your ActiveRecord models. Well, we’ve been using it in more and more of our projects, and we’ve just finished adding some super cool controller tests.

Check it out!

Controller Macros

Right off the bat, you get some pretty little test helpers:

class UsersControllerTest < Test::Unit::TestCase
  context "on GET to :show for first record" do
    setup do
      get :show, :id => 1

    should_assign_to :user
    should_respond_with :success
    should_render_template :show

    should "do something else really cool" do
      assert_equal 1, assigns(:user).id

That bit of code makes five functional tests, and is super easy to read. To take it a step further - if you’ve been a good boy and have kept to the latest restful standards in your controllers, then you’re in luck.


You can produce an entire set of tests (over 40) for both html and xml formats through the should_be_restful helper.

class UsersControllerTest < Test::Unit::TestCase

  def setup
    @controller =
    @request    =
    @response   =
    @user       = User.find(:first)

  should_be_restful do |resource|
    resource.parent = :country
    resource.create.params = { :name => "bob",
      :email => '',
      :age => 13
    resource.update.params = { :name => "sue" }

Should_be_restful is very configurable, but as the name states, it’s only intended for testing restful controllers. We’ve finished tests for the HTML and XML formats, and RSS, YAML, and JSON will soon be on their way.

Check out the project page and the documentation for more information and examples.