Rails functional tests and 406 errors

Posted by david
on 21 Mar 2009 at 22:57

So I have an controller method that responds to multiple formats, like so.

1
2
3
4
5
6
def index
  respond_to do |format|
    format.html
    format.pdf
  end
end

Simple enough. So what do the tests look like?

1
2
3
4
5
6
7
8
9
def test_default_index
  get :index
  assert_response :success
end

def test_pdf_index
  get :index, :format => :pdf
  assert_response :success
end

Again, nothing fancy. Let’s run the test and …


  1) Failure:
test_pdf_index(FoosControllerTest)

    [stacktrace omitted for brevity]

Expected response to be a <:success>, but was <406>

2 tests, 2 assertions, 1 failures, 0 errors

Ruh-roh. How could such a simple test fail, and what’s a 406 response? Well, it’s the numeric code for a Not Acceptable HTTP response, so it looks like the HTTP request is borked. Perhaps the log file will reveal something, and indeed it does.


Processing FoosController#index to pdf (for 0.0.0.0 at 2009-03-21 22:57:10) [GET]
  Parameters: {"format"=>:pdf, "action"=>"index", "controller"=>"foos"}

Looks like we can’t use a symbol for the format in the test. Sure enough, a quick change to the failing test,

1
2
3
4
def test_pdf_index
  get :index, :format => 'pdf'
  assert_response :success
end

and the results are as expected.


2 tests, 2 assertions, 0 failures, 0 errors

Update: Looks like the code formatting is fubar.

Update II: The code formatting is now fixed. See the explanation if you’re interested in the details.

Comments

Sorry, comments are closed.