In a Rails 8.1 integration test, how do you sign in a user with Devise 5, and why might an unconfirmed user still be bounced?
answer
- include Devise::Test::IntegrationHelpers
- Warden test mode, login_as on next request
- ControllerHelpers for controller and view tests
- sign_in(user, scope: :admin) keyword only
- activatable hook still checks confirmed_at
basics
~20 sInclude Devise::Test::IntegrationHelpers and call sign_in(user) before the request; it logs the user in through Warden's test mode instead of posting the form. Devise's activation check still runs, so an unconfirmed or locked user is signed straight out.
solid answer
~40 sIn `ActionDispatch::IntegrationTest` (and RSpec request or system specs) include `Devise::Test::IntegrationHelpers`. Its `sign_in(user)` calls Warden's `login_as`, which queues a `set_user` for the next request; the module turns on `Warden.test_mode!` in setup and resets it in teardown. Controller and view tests that skip the router use `Devise::Test::ControllerHelpers`, which builds a `Warden::Proxy` in `request.env` and needs `devise.mapping` set when the controller is a Devise one. Devise 5 removed `Devise::TestHelpers` and the positional scope, so it is `sign_in(user, scope: :admin)`. Neither helper skips `active_for_authentication?`: the activatable hook runs when the user is set or fetched, so a fixture without `confirmed_at` under `:confirmable`, or with `locked_at`, is logged out and redirected.
code
ruby · 18 lines# test/integration/invoices_test.rb
require "test_helper"
class InvoicesTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
test "a confirmed tenant sees invoices" do
sign_in users(:acme_admin)
get invoices_path
assert_response :success
end
test "an unconfirmed tenant is bounced" do
sign_in users(:pending_tenant)
get invoices_path
assert_redirected_to new_user_session_path
end
endgo deeper
Include Devise::Test::IntegrationHelpers and call sign_in(user) before the request instead of filling in the form.
Explain IntegrationHelpers versus ControllerHelpers, Warden test mode, the scope: keyword and the devise.mapping env key.
Diagnose the redirect from an unconfirmed or locked fixture through the activatable hook, and keep one real form-based sign-in test.
Balance fast helper-based sign-in across the suite against a few end-to-end flows that keep the real login path covered.
## Two helper modules for two kinds of test Devise provides test helpers so a test does not have to fill in the sign-in form before every request. Which module you include depends on whether the test goes through the full Rack stack: | Test type | Module | How `sign_in` works | |---|---|---| | `ActionDispatch::IntegrationTest` (Rails' generated controller tests), RSpec `type: :request`, system tests | `Devise::Test::IntegrationHelpers` | Warden's `login_as` on the next request | | `ActionController::TestCase`, RSpec `type: :controller` and `type: :view` | `Devise::Test::ControllerHelpers` | stores the user directly in a test `Warden::Proxy` | Rails' generated controller tests have been integration tests since Rails 5, so most apps only need `IntegrationHelpers`. ## How `IntegrationHelpers#sign_in` works 1. Including the module includes `Warden::Test::Helpers` and registers a setup step that calls `Warden.test_mode!` and a teardown step that calls `Warden.test_reset!`. 2. `sign_in(user)` finds the scope from the record (or takes `scope:`) and calls `login_as(user, scope: scope)`. 3. `login_as` queues a block with `Warden.on_next_request`. When the next request reaches the `Warden::Manager` middleware, the block calls `proxy.set_user(user, event: :authentication)`, as a real sign-in would. 4. Warden writes the user's key into the session cookie, so later requests in the same test stay signed in until `sign_out :user`. No password is checked and no `POST /users/sign_in` happens. `sign_out` works the same way through `logout`. ## How `ControllerHelpers#sign_in` works A controller test calls the action directly, without the middleware, so there is no `env['warden']`. `ControllerHelpers` creates a `Warden::Manager` and `Warden::Proxy` for the test request and catches `throw :warden` to run the failure app as the middleware would. Its `sign_in` stores the user through Warden's session serializer. When testing a Devise controller or a subclass, set `@request.env["devise.mapping"] = Devise.mappings[:user]`, because the mapping normally comes from the router. ## Changes in Devise 5 - `Devise::TestHelpers` is gone; include `Devise::Test::ControllerHelpers` instead. - The positional scope `sign_in(user, :admin)` is gone; write `sign_in(user, scope: :admin)`. ## Why an unconfirmed user is still bounced Both helpers skip the password check, but **not** Devise's account-state check. Devise registers a Warden `after_set_user` hook (the activatable hook) that runs whenever a user is set, including on `login_as`'s `set_user` and when a stored user is fetched from the session: - it calls `active_for_authentication?`; - under `confirmable`, that is false while `confirmed_at` is `nil` (with the default `allow_unconfirmed_access_for` of `0.days`); - under `lockable`, it is false while the account is locked (`locked_at` set and not yet expired); - when false, the hook calls `warden.logout(scope)` and throws with the `inactive_message`, so the request is redirected to the sign-in page with "You have to confirm your email address before continuing". The fix belongs in the test data: set `confirmed_at` in the fixture, call `user.confirm` or `skip_confirmation!` in the factory, and leave `locked_at` empty unless the test is about locking. ## Fixtures and factories for Devise users Test data has to satisfy the same columns production users have: - **Fixtures** cannot call `password=`, so they set `encrypted_password` directly; ERB in the fixture file can produce it with `Devise::Encryptor.digest(User, "secret123")`, which applies the model's stretches and pepper. - **Factories** can assign `password` and `password_confirmation` normally, because the model's `password=` writer hashes them. - Under `confirmable`, add `confirmed_at` to every user that should be able to sign in; under `lockable`, leave `failed_attempts` at 0 and `locked_at` empty. - Keep one deliberately unconfirmed and one locked user, so the bounce itself is tested. ## Practical setup - The generated initializer sets `config.stretches = Rails.env.test? ? 1 : 12`, so creating users in tests stays fast. - Add the include once: in `ActionDispatch::IntegrationTest` via `test_helper.rb`, or with `config.include Devise::Test::IntegrationHelpers, type: :request` in RSpec. - Keep at least one test that signs in through the real form, so the sign-in page itself stays covered.
- Why does a controller test of a Users::SessionsController subclass fail with a mapping error, while an integration test does not?Devise reads the mapping from the route that matched. A controller test calls the action without the router, so `request.env['devise.mapping']` is empty; set it with `@request.env['devise.mapping'] = Devise.mappings[:user]`. Integration tests go through the routes, so the mapping is found.
- Can IntegrationHelpers' sign_in be used in a Rails system test driven by a real browser?Yes, when the app server runs in the test process, as Rails system tests do. `login_as` registers its block globally with `Warden.on_next_request`, so the next request the browser makes to that server picks it up and the session cookie is set. It is not suitable when the app runs in a separate process.
- sign_in in a test posts the sign-in form and checks the password
- Test sign-in skips every Devise check, including confirmation
- Devise::TestHelpers is the module to include in Devise 5 controller tests
- sign_in(user, :admin) is the way to choose a scope in tests
- Integration tests must set request.env devise.mapping by hand
Assumes Devise 5.0: Devise::TestHelpers and the positional scope argument of sign_in were removed in 5.0.