skip to content

In a Rails integration test, how do assert_response and follow_redirect! verify a booking form that redirects after a successful POST?

level: juniorimportance: should knowfreq 55%

answer

  1. four range symbols
  2. :redirect means any 3xx
  3. assert_redirected_to checks the Location
  4. follow_redirect! raises unless 301/302/303/307/308
  5. returns the new status

basics

~10 s

assert_response :redirect passes for any 3xx and assert_redirected_to checks the Location; follow_redirect! then requests that Location with GET (keeping the verb on 307/308) and returns the new status for assert_response :success.

solid answer

~40 s

In an `ActionDispatch::IntegrationTest`, `post bookings_url, params: { booking: {...} }` sends the form through routing, middleware and the controller. `assert_response` accepts four range symbols, `:success` (2xx), `:redirect` (3xx), `:missing` (404) and `:error` (5xx), or any Rack status symbol or integer such as `:see_other` or `:unprocessable_content`. `assert_redirected_to booking_url(Booking.last)` checks that it redirected and where to. `follow_redirect!` raises a `RuntimeError` ("not a redirect!") unless the status is 301, 302, 303, 307 or 308. Otherwise it requests the `Location` with GET, or with the same verb for 307 and 308, sets the referer, and returns the new status. I then assert on the landing page with `assert_response :success` and `assert_in_body`, new in Rails 8.1, or `assert_select`.

code

ruby · 19 lines
ruby
class BookingFlowTest < ActionDispatch::IntegrationTest
  test "booking a spot lands on its confirmation" do
    post bookings_url, params: { booking: {
      spot_id: spots(:level_two_a).id,
      arrives_at: 1.hour.from_now,
      departs_at: 3.hours.from_now
    } }

    assert_redirected_to booking_url(Booking.last)
    follow_redirect!
    assert_response :success
    assert_in_body "Level 2, spot A"
  end

  test "an overlapping booking re-renders the form" do
    post bookings_url, params: { booking: { spot_id: spots(:taken).id } }
    assert_response :unprocessable_content
  end
end

go deeper

for a junior

Recall the four range symbols for assert_response and the post, assert_redirected_to, follow_redirect!, assert_response :success sequence.

for a middle

Explain how follow_redirect! picks GET or the original verb, what it raises on a non-redirect, and how a 422 re-render is asserted with :unprocessable_content.

for a senior

Use show_exceptions :rescuable and explicit status assertions so failing integration tests explain themselves, and avoid tests that only check a redirect happened.

for a principal

Set suite conventions for asserting outcomes such as status, target and visible content rather than internals, so controller refactors do not ripple through tests.

## The request helpers In an **`ActionDispatch::IntegrationTest`** the helpers `get`, `post`, `patch`, `put`, `delete` and `head` each send one request through the whole application in the same process. They take a path or a route helper plus keyword options: - `params:` - form fields, nested the way the controller expects them (`{ booking: { spot_id: 4 } }`). - `headers:` - extra request headers. - `as: :json` - encodes the params as JSON and sets the JSON content type and `Accept` header. - `xhr: true` - marks the request as an Ajax request. Each helper returns the integer status. Afterwards `response`, `request`, `cookies` and `session` describe the last exchange, and the cookie jar carries over to the next request in the same test. ## assert_response `assert_response` checks the status of the last response. It accepts three kinds of argument: | Argument | Passes when | |---|---| | `:success` | status is 200-299 | | `:redirect` | status is 300-399 | | `:missing` | status is exactly 404 | | `:error` | status is 500-599 | | any Rack status symbol, e.g. `:see_other`, `:unprocessable_content` | status equals that code (303, 422) | | an integer, e.g. `404` | status equals that number | The four range symbols are Rails' own shorthands. Any other symbol is looked up in Rack's status table, so `:unprocessable_content` is the current name for 422 on Rack 3.1 and later; `:unprocessable_entity` is the obsolete Rack name and warns on Rack 3.2. ## assert_redirected_to `assert_redirected_to booking_url(Booking.last)` first asserts the response is a redirect, by default with `:redirect`, or with `status: :see_other` if you pass one. It then compares the `Location` header with the URL, record, route hash or regular expression you give it. It checks where the redirect points; it does not request that page. ## follow_redirect! `follow_redirect!` performs the next hop for you: 1. It checks the last response is a redirect, meaning status 301, 302, 303, 307 or 308. If not, it raises `RuntimeError` with a message such as `not a redirect! 200 OK`. 2. It picks the verb: the **same verb** for 307 and 308, **GET** for everything else. 3. It sets the `HTTP_REFERER` header to the previous URL unless you passed one. 4. It requests the `Location` and **returns the new status**. A plain `redirect_to` answers 302, and the scaffold's update and destroy redirects pass `status: :see_other` (303). Both are followed with GET. ## Failure paths worth asserting - A failed save that re-renders the form answers 422: `assert_response :unprocessable_content`. - The generated `config/environments/test.rb` sets `config.action_dispatch.show_exceptions = :rescuable`. An exception Rails maps to a status, such as `ActiveRecord::RecordNotFound` to 404, is rendered as that response. Any other exception is raised straight into the test. - After `follow_redirect!`, check the page itself: `assert_in_body "Level 2, spot A"` (added in Rails 8.1, with `assert_not_in_body`), or `assert_select` for structure. ## Why this pair matters Post/redirect/get is the shape of almost every HTML form in Rails. Asserting only `:redirect` proves nothing about where the visitor lands, and calling `follow_redirect!` without checking the target can hide a redirect to the wrong page. The usual sequence is: assert the redirect target, follow it once, then assert the landing page's status and content. ## The same pattern for a JSON endpoint An API action usually answers `201 Created` with a body instead of redirecting: - send the request with `post api_bookings_url, params: { booking: {...} }, as: :json`; - assert `assert_response :created`, which is a Rack status symbol checked exactly; - read the body with `response.parsed_body`, which parses a JSON response into an `ActiveSupport::HashWithIndifferentAccess`, so string and symbol keys both work; - for a validation failure, assert `:unprocessable_content` and check the error keys in the parsed body. `follow_redirect!` has no role there, because nothing redirects; calling it would raise the same `not a redirect!` error.

  • In a Rails integration test, what happens if you call follow_redirect! after a 200 response?
    It raises a `RuntimeError` with a message like `not a redirect! 200 OK`, because it only follows 301, 302, 303, 307 and 308. That usually means the action re-rendered a form, often a failed validation answering 422, or the 200 came from the wrong branch. Assert the status first so the failure message says what happened.
  • Why does get booking_url(id: 0) give assert_response :not_found instead of an exception in a generated Rails 8.1 test environment?
    The generated `test.rb` sets `config.action_dispatch.show_exceptions = :rescuable`. Exceptions listed in `rescue_responses`, such as `ActiveRecord::RecordNotFound` mapped to 404, are rendered as that status. Unmapped exceptions like `NoMethodError` still raise into the test.

  • assert_response :success also passes for a 302 redirect.
  • follow_redirect! re-sends the original POST for every redirect status.
  • assert_redirected_to requests the target page and checks it renders.
  • :unprocessable_entity is the current status symbol for a failed form save.
  • assert_response :missing passes for any 4xx status.

Assumes Rails 8.1 on Rack 3.1+; assert_in_body is new in 8.1 and :unprocessable_content replaced Rack's :unprocessable_entity name.