loading...

follow_redirect! in Rails request specs

prathamesh profile image Prathamesh Sonpatki ・1 min read

In integration tests we test the complete scenario of a user interaction. Typically it means, we hit different URLs of the application. In such situations, it may happen that one controller action redirect to another action in same or different controller and we need to visit that page to test the further part of the scenario.

Typical example will be user signing up on our website. After signing up the user must be shown welcome screen. In an integration test, we submit the sign up form and then we need to test whether user sees welcome text or not.

  post "/join", params: user_params
  expect(response).to redirect_to("/welcome")
  # Test that welcome page displays certain content

Rails provides a handy method follow_redirect! for this purpose. As the name suggests, it follows a redirect response.

  post "/join", params: user_params
  expect(response).to redirect_to("/welcome")

  follow_redirect!

  # get "/welcome" is automatically hit with current user as the new 
  # user

In RSpec, we can use this method in the request specs. If you are using minitest with Rails then you can use this method in integration tests.
This method is very handy and helps in testing a complex scenario involving multiple steps a breeze.

Happy testing!

Posted on by:

prathamesh profile

Prathamesh Sonpatki

@prathamesh

Prathamesh Sonpatki is consultant experienced in Ruby, Ruby on Rails.

Discussion

markdown guide