Testing HTTP Requests with Response-Related Assertions

Problem

Your functional tests issue requests using any of the five request types of the HTTP protocol. You want to test that the responses to these requests are returning the expected results.

Solution

Use assert_response to verify that the HTTP response code is what it should be:

def test_successful_response
 get :show_sale
 assert_response :success
end

To verify that the correct template is rendered as part of a response, use assert_template:

def test_template_rendered
 get :show_sale
 assert_template "store/show_sale"
end

Assuming that a logout action resets session information and redirects to the index action, you can assert successful redirection with assert_redirected_to:

def test_redirected
 get :logout
 assert_redirected_to :controller => "store", :action => "index"
end

Discussion

The assert_response method takes any of the following status codes as a single symbol argument. You can also pass the specific HTTP error code.

  • :ok (status code is 200)
  • :success (status code is within 200..299)
  • :redirect (status code is within 300..399)
  • :forbidden (status code is 403)
  • :missing (status code is 404)
  • :not_found (status code is 404)
  • :error (status code is within 500..599)
  • Status code number (the specific HTTP status code as a Fixnum)

assert_template takes the page to the template to be rendered relative to ./app/views of your application and without the file extension.

Most assertions in Rails take a final, optional argument of a string message to be displayed should the assertion fail.

See Also