Welcome to Giant Robots Smashing Into Other Giant Robots — a weblog about development, business, design and technology — written by thoughtbot.

Shoulda gets busy with your controllers

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

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

    should_assign_to :user
    should_respond_with :success
    should_render_template :show
    should_not_set_the_flash

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

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.

should_be_restful

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

class UsersControllerTest < Test::Unit::TestCase
  load_all_fixtures

  def setup
    @controller = UsersController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
    @user       = User.find(:first)
  end

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

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.


About this entry

 

thoughtbot is hiring

We are hiring web developers and web designers in both Boston and New York, NY.

What are we up to?

We built Shoulda, an eclectic set of additions to Test::Unit; Paperclip to manage uploaded files without hassle; Jester, a REST/ActiveResource client library written in Javascript, and Squirrel, an enhancement for ActiveRecord's find syntax; — amongst some other projects.


Chad (President) and Jon (CTO) co-authored a technical book titled Pro Active Record: Databases with Ruby and Rails, which explores the ins and outs of the ActiveRecord ruby library. You can buy it today at Amazon.com.

About thoughtbot, inc.

We are a small web application development consulting business, with offices in Boston, MA and New York, NY. If you're looking to find a team for your next web development project or your new web application — get in touch.