Using assert_select and friends in Helper Tests

July 6, 2009 Pivotal Labs

Assertions such as assert_select, assert_tag, and css_select are powerful tools in view tests. Since view helpers generate a chunk of HTML, it is sometimes practical to use these assertions to test their return value.

If you attempt to use assert_select it will fail because there has not been a call to render, as is done in a view test. To get around this you can store the result of the helper method in @response.body. Once @response.body is populated, the assertions will work like expected.

Update: For people using RSpec, Pat Maddox posted a helpful suggestion in the comments showing how to use have_tag to accomplish the same thing in RSpec style.

Example

describe TagsHelper do
  describe "#tag_list"
    describe "when the user is not an admin"

      it "should not have links to delete the tags" do
        @response.body = helper.tag_list
        assert_select "a", 0
      end

    end
  end
end

Reality Check

If you find yourself writing a helper method that generates a lot of HTML, or is overly complex, stop and ask yourself whether it would be more appropriate to move this code into a partial.

Attribution

Credit for this tip goes to a comment by Bill Siggelkow on the Nuby on Rails blog.

About the Author

Biography

More Content by Pivotal Labs
Previous
How to make Firebug 1.4 behave sanely
How to make Firebug 1.4 behave sanely

As has been noted a few times, the new activation model in Firebug 1.4 is kind of psychotic. The main prob...

Next
The Engine Yard Cloud: A Programmable Deployment Platform
The Engine Yard Cloud: A Programmable Deployment Platform

Ezra Zygmuntowicz of Engine Yard details their new Flex cloud hosting product, including the extensive use ...

How do you measure digital transformation?

Take the Benchmark