More Testing Goodness

Tammer Saleh

So, some test helpers that we’ve been working on here at thoughtbot. Here’s what we’ve got going on for the models:

class ArticleTest < Test::Unit::TestCase
  should_belong_to :article_type
  should_have_and_belong_to_many :products
  should_have_one :image
  should_have_many :widgets, :through => :widgetization
  should_require_attributes :author, :title, :body
end

Pretty nice stuff, and it does away with about 50% of the tests we would normally write. But, the controllers are proving to be a bit more tenacious. We aren’t trying to be too ambitions—we really just want to deal with the most common restful controller actions. We want these tests to pretty much ensure that the controller “acts like a controller”. This way, any deviant behavior it may have will really stand out in the test file. This is what we have, so far.

class ArticlesControllerTest < Test::Unit::TestCase
  fixture :articles

  def setup
    @controller = ArticlesController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
  end

  should_get_index
  should_get_new
  should_post_to_create :item_params => { :title => "Blah",
                                          :body => 'super',
                                           :author => 'Someone'
                                        },
                        :redirect_params => { :id => 'blah' }
  should_get_show :first
  should_get_edit :first
  should_put_to_update  :first, :item_params => { :title => "Blah" },
                                 :redirect_params => { :id => 'blah' }
  should_post_to_destroy :first
end

These test everything that the autogenerated scaffold file tests, and a bit more. They should deal with nested paths, and strange values from ar.to_param. I’m hoping that our loyal readers will give some insight in ways to simplify the calling signatures of the helpers. Also, let me know if you can’t tell what they do just from reading the code above. If you can’t, then the tests aren’t doing their job.