skip to content

In a Rails 8.1 app built with the authentication generator, what does sign_in_as do in an integration test, and why can't a system test call it?

level: middleimportance: nice to knowfreq 22%

answer

  1. test/test_helpers/session_test_helper.rb
  2. a real Session row
  3. signed session_id cookie
  4. on_load(:action_dispatch_integration_test)
  5. added with Rails 8.1.0

basics

~20 s

sign_in_as(user) creates a Session row for the user, sets Current.session and writes a signed session_id cookie into the integration test's cookie jar. It is included only into ActionDispatch::IntegrationTest, so system tests sign in through the login form instead.

solid answer

~40 s

Since Rails 8.1.0, `bin/rails generate authentication` also writes `test/test_helpers/session_test_helper.rb` and requires it from `test_helper.rb`. `SessionTestHelper#sign_in_as(user)` calls `user.sessions.create!`, stores the session in `Current.session`, builds a signed `session_id` value with a test request's cookie jar and copies it into the integration session's `cookies`, so the next `get` or `post` is authenticated exactly as after a real login. `sign_out` destroys the session and deletes the cookie. The module is added through `ActiveSupport.on_load(:action_dispatch_integration_test)`, so it exists in `ActionDispatch::IntegrationTest` only. A system test inherits `ActiveSupport::TestCase` through `ActionDispatch::SystemTestCase` and drives a real browser whose cookies the test cannot write this way, so it signs in by visiting the sign-in page and submitting the generated form with a fixture user's password.

code

ruby · 14 lines
ruby
class MeditationsTest < ActionDispatch::IntegrationTest
  test "signed-in users see their meditations" do
    sign_in_as users(:one)
    get meditations_path
    assert_response :success
  end

  test "signed-out users are sent to sign in" do
    sign_in_as users(:one)
    sign_out
    get meditations_path
    assert_redirected_to new_session_path
  end
end

go deeper

for a junior

Use sign_in_as users(:one) before requests in integration tests, and sign_out to test the signed-out path.

for a middle

Explain the Session row, the signed cookie and why the helper is included only into integration tests through an on_load hook.

for a senior

Design sign-in helpers per test type, including a form-based one for system tests, and account for the session rows they create.

for a principal

Decide how authentication shortcuts in tests are kept honest, so tests skip slow steps without bypassing the code paths production uses.

## Where the helper comes from Rails 8's authentication generator builds password-based sign-in from plain Rails parts: a `User` with `has_secure_password`, a `Session` model with one row per signed-in device, an `Authentication` concern, and controllers for sessions and password resets. Rails **8.1.0** added a test helper to the files it writes when the app uses Minitest: - `test/test_helpers/session_test_helper.rb`, defining `SessionTestHelper`; - a `require_relative "test_helpers/session_test_helper"` line injected into `test/test_helper.rb`, after `require "rails/test_help"`. Apps generated on 8.0 do not have it unless it is added by hand. ## What sign_in_as does The generated method is short: ```ruby module SessionTestHelper def sign_in_as(user) Current.session = user.sessions.create! ActionDispatch::TestRequest.create.cookie_jar.tap do |cookie_jar| cookie_jar.signed[:session_id] = Current.session.id cookies["session_id"] = cookie_jar[:session_id] end end def sign_out Current.session&.destroy! cookies.delete("session_id") end end ``` Step by step: 1. **A real `Session` row** is created for the user, the same record a real login creates. 2. **`Current.session`** is set in the test thread, which is convenient for code under test that reads it directly. 3. **A signed cookie value** is produced with a throwaway test request's cookie jar, because the integration session's `cookies` hold raw strings and cannot sign them. 4. **The signed value is copied** into the integration session's `cookies["session_id"]`, so the next request sends it. The app's `Authentication` concern then finds the session with `Session.find_by(id: cookies.signed[:session_id])`, exactly as for a browser that logged in through the form. ## Where it is available The file ends with: ```ruby ActiveSupport.on_load(:action_dispatch_integration_test) do include SessionTestHelper end ``` That hook runs when `ActionDispatch::IntegrationTest` is loaded, so: | Test class | `sign_in_as` available? | How to sign in | |---|---|---| | `ActionDispatch::IntegrationTest` | yes | `sign_in_as users(:one)` | | `ApplicationSystemTestCase` | no | visit the sign-in page and submit the form | | `ActiveSupport::TestCase` (model) | no | not needed; call methods with the user | | `ActionMailer::TestCase` | no | not needed | ## Why system tests cannot use it A system test inherits from `ActionDispatch::SystemTestCase`, which is a subclass of `ActiveSupport::TestCase`, not of the integration test class, so the hook never includes the module. Even if it were included, the integration session's `cookies` belong to Rails' in-process test client; in a system test the cookies live in Chrome, and setting `Current.session` in the test thread does not reach the Puma thread's request. The reliable approach is the real form: ```ruby def sign_in_through_form(user) visit new_session_url fill_in "email_address", with: user.email_address fill_in "password", with: "password" click_on "Sign in" end ``` The generated `users.yml` fixture sets each user's `password_digest` from `BCrypt::Password.create("password")`, so "password" is what such a helper types. ## What sign_in_as skips The helper is a shortcut, so it deliberately leaves things out: - It never calls `SessionsController#create`, so `User.authenticate_by`, the password check and the controller's `rate_limit` on sign-in are not exercised. - The `Session` row has no `user_agent` or `ip_address`, which the real login records from the request. - `Current.session` is set only in the test thread; each request still resolves its own session from the cookie. That is why a suite keeps at least one test that signs in through `post session_path` with real credentials, and uses `sign_in_as` everywhere else to avoid repeating it. ## Typical use in a meditation app - `sign_in_as users(:one)` then `get meditations_path` and `assert_response :success`. - `sign_out`, then the same request, then `assert_redirected_to new_session_path`. - Combine with `assert_difference "Session.count", 1` when the test is about creating sessions, remembering that `sign_in_as` itself creates one. ## Pitfalls - Expecting `sign_in_as` in an app generated with Rails 8.0, or with RSpec, where the test-unit templates were not used. - Counting sessions after `sign_in_as` without accounting for the row it created. - Calling it in a system test and getting `NoMethodError`.

  • Why does sign_in_as build the cookie through ActionDispatch::TestRequest.create.cookie_jar?
    The app reads `cookies.signed[:session_id]`, so the value must carry a valid signature made with the app's secret. The integration session's `cookies` hold raw strings, so the helper signs the value with a test request's cookie jar, which has the app's key generator, and copies the signed string across.
  • How do you sign in inside a system test of the same app?
    Through the browser: visit the sign-in page, fill in the email address and password of a fixture user and click "Sign in". The generated users fixture builds its digest from the password "password", and a small helper method in `ApplicationSystemTestCase` keeps tests short.

  • sign_in_as stubs current_user without creating a Session row
  • sign_in_as is available in every Rails test class
  • sign_in_as writes an unsigned session_id cookie
  • The Rails 8.0 authentication generator already wrote sign_in_as
  • Setting Current.session in a system test signs the browser in

Assumes Rails 8.1, whose authentication generator added SessionTestHelper with sign_in_as and sign_out (8.1.0); apps generated with 8.0 lack it unless it is added by hand.