Using assert_select outside of the controller context

Testing your Rails helpers in an isolated context is made a lot easier with Geoffrey Grosenbach’s HelperTestCases. One thing however is still missing. assert_select is great for cutting through the response bodies in your functional and integration tests. Here’s how to use it outside those contexts:


require File.dirname(__FILE__) + ‘/../../test_helper’
require ‘ostruct’

class BuyerHelperTest < HelperTestCase

include BuyerHelper def test_should_render_latest_posts # capture the output of your helper html = render_latest_posts(feed_uri) @response = OpenStruct.new :body => html, :headers => {“Content-Type” => “text/html”} assert_select “table.latest_posts tr” do |rows| ... end end

end

If you’re already using a mocking/stubbing library in your tests, you can forgo the OpenStruct stuff (including ‘ostruct’), in favor of just stubbing it out:

<pre>@response = stub(:body => html, :headers => {"Content-Type" => "text/html"})</pre>

For Rails 2.0 you’ll also need to make some adjustments:

<pre>@response = stub(:body => html, :content_type => "text/html")</pre>

2 Responses to “Using assert_select outside of the controller context”


  1. Gravatar Icon 1 Gavin Stark

    I also use this to assert_select when all I have is html.

    test_helper.rb:

    def assert_select_from_html( html, *args, &block )
    html_document = HTML::Document.new( html ).root
    assert_select( html_document, *args, &block )
    end

    Then I can write:

    assert_select_from_html my_helper_method, “css.selector” do …

  2. Gravatar Icon 2 Jason Perry

    Oh that’s slick, and makes a little more sense than my round about way of doing it…

Leave a Reply