In Rails 8.1 tests, how are Current attributes kept from leaking between tests, and how do you set Current.account for one test?
answer
- executor_around_test_case in load_defaults 7.0
- CurrentAttributes::TestHelper clears in setup and teardown
- assign in setup or use Current.set
- 8.1 saves and restores around requests and jobs
- a request starts with an empty Current
basics
~20 sRails clears Current around every test: a new app runs each test inside the executor, and older configurations clear it in setup and teardown. Assign Current.account in setup or wrap code in Current.set; requests and performed jobs start their own empty Current.
solid answer
~40 sA new app's `load_defaults` turns on `config.active_support.executor_around_test_case` (a 7.0 default), so each `ActiveSupport::TestCase` runs inside `Rails.application.executor`, and the executor's completion hook clears `Current` when the test ends. Without that setting, Rails includes `ActiveSupport::CurrentAttributes::TestHelper`, which calls `CurrentAttributes.clear_all` before setup and after teardown; rspec-rails' Rails example groups include the same helper. Either way one test's `Current.account` cannot leak into the next. To set it, assign `Current.account = accounts(:acme)` in `setup`, or wrap the exercised code in `Current.set(account: accounts(:acme)) { ... }`. Code the test calls through the executor, an integration request or `perform_enqueued_jobs`, starts with an empty `Current`, and since 8.1.0 the test's own values are saved and restored around it instead of being wiped. So sign in through the app for requests, and pass accounts to jobs as arguments.
go deeper
Recall that Rails clears Current between tests automatically and that setup is the place to assign Current.account for a test class.
Explain the two mechanisms, executor around each test or the clear_all helper, and why requests and performed jobs start with an empty Current.
Use tests to expose hidden Current dependencies: run jobs through perform_enqueued_jobs, keep an empty-Current case, and know the 8.1 save-and-restore change.
Treat heavy Current setup in tests as design feedback, and set conventions for which code may read Current at all.
## Why tests need a reset too A test suite runs many tests on the same thread, one after another. If a model test sets `Current.account = accounts(:acme)` and nothing cleared it, the next test would start with Acme as the tenant and pass or fail depending on test order. Rails clears `Current` around every test, through one of two mechanisms. ## How Rails isolates tests | Setting | Mechanism | Effect | |---|---|---| | `config.active_support.executor_around_test_case = true` (set by `load_defaults "7.0"` and later) | `ActiveSupport::Executor::TestHelper` runs each test inside `Rails.application.executor.perform` | `Current` starts fresh and is cleared by the executor's completion hook | | setting off | `ActiveSupport::CurrentAttributes::TestHelper` and the execution-context helper | `clear_all` in `before_setup` and `after_teardown` | A new Rails 8.1 app uses the first row. rspec-rails' `RailsExampleGroup` includes `ActiveSupport::CurrentAttributes::TestHelper` as well, so model, request and job specs get the same clearing. ## Setting values in a test Two patterns, both safe because of the reset: ```ruby class ContactTest < ActiveSupport::TestCase setup do Current.account = accounts(:acme) Current.user = users(:dana) end test "new contacts default to the current account and creator" do contact = Contact.create!(name: "Ada") assert_equal accounts(:acme), contact.account assert_equal users(:dana), contact.creator end test "an admin import records the ops user" do Current.set(user: users(:ops)) do assert_equal users(:ops), Contact.create!(name: "Bulk").creator end end end ``` - Assigning in `setup` suits a test class where every test acts as the same tenant. - `Current.set(...) { }` suits one test that needs a different value for part of its body, because it restores the previous value afterwards. ## Requests and jobs inside tests Code that the test enters **through the executor** starts its own execution: 1. An **integration or system request** passes through the `ActionDispatch::Executor` middleware, which begins a fresh execution, so values set in the test body are not visible inside the controller. Set up state the way a user would, by signing in through the app or a test helper, and let the app's `before_action` set `Current`. 2. A **job run by `perform_enqueued_jobs`** or by Active Job's test helpers runs under the reloader and executor, so it also starts with an empty `Current`. That is useful: a job that relies on `Current` instead of its arguments fails in the test, as it would on a worker. Rails 8.1.0 changed what happens to the test's own values in this situation. Previously, calling into executor-wrapped code from a test could wipe the test's `Current` state, so `Current.user` set before a request was `nil` after it. Now the state is saved when the executor is re-entered and restored when it completes, so assertions after the request still see the test's values. ## Testing code that reads `Current` A test that needs many `Current` values before anything works is a signal, not just a chore. It means many methods depend on hidden context. Two habits keep tests honest: - prefer methods that take `account:` or `user:` arguments, and test them by passing values; - keep one or two tests that run the code with `Current` empty, which is what a console or job will do, to prove it fails loudly rather than widening a query. ## RSpec With rspec-rails, the same clearing applies, because its `RailsExampleGroup` includes `ActiveSupport::CurrentAttributes::TestHelper`. Values are set the same way: `before { Current.account = accounts(:acme) }` for a group, or `Current.set(...) { }` inside one example. Request specs behave like integration tests, so the request starts with an empty `Current` and must set it through the app. ## Common mistakes - Setting `Current` in a test and expecting an integration request to see it. - Writing a custom `teardown { Current.reset }` that duplicates what Rails already does. - Testing a job with `perform_now` inside a block that set `Current`, which hides the missing-argument bug the worker will hit.
- Why does a value set with `Current.account =` in a test not reach the controller in an integration test?The request goes through the `ActionDispatch::Executor` middleware, which starts a new execution with its own, empty `Current`. The controller sees only what its own callbacks set. Sign in or choose the tenant the way a real request would, for example via the subdomain or a sign-in helper.
- How would you test that `ContactImportJob` does not depend on `Current` being set?Enqueue it with explicit arguments and run it through `perform_enqueued_jobs`, which executes the job in a fresh execution with an empty `Current`. Assert the contacts belong to the passed account. If the job secretly read `Current.account`, the test fails as it would on a production worker.
- You must call Current.reset in every test's teardown or values leak.
- Setting Current.account in a test makes it visible inside integration requests.
- perform_enqueued_jobs runs jobs with the test's Current values already set.
- In Rails 8.1, any request made from a test permanently wipes the test's Current.
- rspec-rails gets no Current clearing, so RSpec suites always leak values.
Assumes Rails 8.1 with load_defaults 8.1: tests run inside the executor (a 7.0 default), and since 8.1.0 re-entering the executor from a test saves and restores Current.