assert_select from arbitrary text
A useful testing method in Rails is assert_select. In a functional test, you can use it to make sure the controller’s response has the HTML you expect:
should "display the suggestion as a link" do assert_select 'a[href=?]', @click_url, @display_url end
… says there should be an <a> tag with the given href attribute and content. Clearer and less brittle than computing a string and searching for it.
But what if you want to assert something about the HTML structure of something that isn’t the controller response? Like, if you want to look for a link in the flash hash?
I just added this to my test_helper.rb:
class ActiveSupport::TestCase def assert_select_from(text, *args) @selected = HTML::Document.new(text).root.children assert_select(*args) end end
Now in my tests I can use the full power of assert_select on an arbitrary string:
should "provide an undo/delete link" do assert_select_from(flash[:notice], 'a[href=?]', venue_path(assigns(:venue)), 'undo') end
To make this work in Rails 2.3.2, I had to change it to:
def assert_select_from(text, *args)
@selected = HTML::Document.new(text).root
assert_select(@selected, *args)
end
Comment by Bob — January 25, 2010 @ 9:06 am
this was very helpful. thanks!
Comment by willsu — February 25, 2010 @ 10:07 pm