Archive for October, 2007

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>