Using Webrat assertions in your functional tests

I’m tired of assert_select. The multi-parameter syntax is confusing and hard to follow, and the semantics aren’t clear. For example, in a test like this:

assert_select "div[class=note]" do
  assert_select "div[class=company_name]", company_name
end

Are we ensuring that there is at least one note div with a company name div, or that all note divs have a company name div? What is that second argument? Is it the text inside the company name div, the number of times that div should be there, or a replacement value for imbedded question marks (hint: all three).

Also, why are we specifying what type of element we see in our tests? In the days of jQuery and XPaths, the element types don’t matter nearly as much as they used to.

Webrat gets it right with assert_have_selector

assert_have_selector ".note .company_name:contains('#{company_name}')"

Much better! Same, consistent XPath selector syntax as jQuery, and much more concise to boot!

Webrat’s firmly aimed at integration testing. Nothing at all wrong with integration testing, but there’s also no reason to leave our functional tests behind.

Wanna use the Webrat assertions in your functional tests as well? Three easy steps:

  1. Require webrat
  2. Include the matchers module
  3. Add a response_body method to your testcase class

Here’s the snippet from my test/test_helper.rb file:

require 'webrat'
class ActionController::TestCase
  include Webrat::Matchers
  def response_body
    @response.body
  end
end

VoilĂ !


Fork and edit this post on Github.