ruby rails testing

ActionController::TestCase provides assert_select to check for specific contents of views in a Rails project. It’s also a nice way to test view helpers with somewhat more complex HTML output (ie. nested nodes by multiple calls to content_tag).

There is a nice and short article by Erik Ostrom that explains how to do that without the response object you’ll normally have when using it to check views. However, it lacked support for nested nodes which can be remedied by adding yield @selected if block_given?.

The modified code snippet to put in test/test_helper.rb is:

class ActiveSupport::TestCase
  def assert_select_from(text, *args)
    @selected = HTML::Document.new(text).root.children
    assert_select(*args)
    yield @selected if block_given?
  end
end

Usage example:

def test_hreview_aggregate_item
  output = hreview_aggregate(:fn => "John Doe's Pawn Shop")
  assert_select_from output, "span.hreview-aggregate" do
    assert_select "span.item" do
      # nb: it's assert_select within the block
      assert_select "span.fn", :text => "John Doe's Pawn Shop"
    end
  end
end
comments powered by Disqus