Test Your respond_to Block

Getting RESTful and wondering how to test your respond_to block in your controller to make sure its returning the right format? Drop these into your test_helper.rb.

def assert_xml
  assert_match 'application/xml', @response.headers['Content-Type']
end
 
def assert_rss
  assert_match 'application/rss+xml', @response.headers['Content-Type']
end

Then in your functional tests, use them like this:

def test_return_xml
  get :index, :format => 'xml'
  assert_xml
end
 
def test_return_rss
  get :index, :format => 'rss'
  assert_rss
end

Yay!

Popularity: 4% [?]

You can skip to the end and leave a response. Pinging is currently not allowed.

2 Thoughts

  1. How about a matching one for setting the Accept header simply?

  2. You mean something like this?

    def test_return_xml
    accept 'text/xml'
    get :index
    assert_xml
    end
    

    That's how you'd do it for pre 1.2 stuff, but I thought the convention was moving towards using formats over accept headers.

Share Your Thoughts?

Please excuse my captcha. But the internets require it these days. Comment triage isn’t billable.