Echographia

making things better, making better things

Saturday, August 22, 2009

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
posted by erik at 8:57 pm  

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress