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