In a Rails test, what does assert_difference check, and how do you assert that a sign-up creates one User and one Session?
answer
- before and after the block
- default difference is 1
- string, lambda, array or hash
- assert_no_difference for the failure path
- returns the block's value
basics
~20 sassert_difference evaluates an expression, runs the block, evaluates it again and asserts the change equals the expected difference, 1 by default. A hash checks several counts: assert_difference({ "User.count" => 1, "Session.count" => 1 }) { post sign_up_path, params: ... }.
solid answer
~40 s`assert_difference` comes from `ActiveSupport::Testing::Assertions`, which every Rails test class inherits. It evaluates each expression before the block, runs the block, evaluates again and asserts `before + difference == after`. The expression may be a string evaluated in the block's binding, a lambda, an array of either sharing one difference, or a hash mapping each expression to its own difference; the default difference is 1 and negatives assert a decrease. For a meditation app's sign-up: `assert_difference({ "User.count" => 1, "Session.count" => 1 }) { post sign_up_path, params: { user: {...} } }`. The failure path uses `assert_no_difference "User.count"`. It returns the block's value, and its failure message names the expression and the actual change. For a non-numeric change, `assert_changes -> { user.reload.plan }, from: "trial", to: "premium"` checks values instead of a count.
code
ruby · 16 linestest "cancelling a subscription removes it" do
subscription = subscriptions(:mia_monthly)
assert_difference "Subscription.count", -1, "subscription should be destroyed" do
delete subscription_path(subscription)
end
end
test "upgrading changes the plan, not the count" do
user = users(:mia)
assert_no_difference "User.count" do
assert_changes -> { user.reload.plan }, from: "trial", to: "premium" do
patch plan_path, params: { plan: "premium" }
end
end
endgo deeper
Write assert_difference and assert_no_difference around a request or a save, and remember the default difference of 1.
Use the hash and lambda forms for several side effects, and explain when assert_changes fits better than a count.
Spot assertions that count too broadly or read cached associations, and make every expected side effect of a request explicit.
Set conventions for how a suite states side effects, so tests document every row a request should and should not create.
## What it checks `assert_difference` is a Rails assertion defined in `ActiveSupport::Testing::Assertions`. Because `ActiveSupport::TestCase` includes that module, it is available in model, integration, mailer, job and system tests alike. It answers one question: **did this block change a number by exactly this much?** The sequence is fixed: 1. Evaluate every expression and remember the values. 2. Run the block. 3. Evaluate every expression again. 4. Assert that each new value equals the old value plus its expected difference. If the block raises, the assertion reports the exception rather than a difference. ## The forms it accepts | Form | Example | Difference | |---|---|---| | String | `assert_difference "User.count"` | 1 by default | | String with difference | `assert_difference "Booking.count", -1` | negative for a delete | | Lambda | `assert_difference -> { user.sessions.count }, 2` | any number | | Array | `assert_difference ["User.count", "Session.count"]` | one shared difference | | Hash | `assert_difference({ "User.count" => 1, "Session.count" => 1 })` | one per expression | | Hash of lambdas | `assert_difference -> { User.count } => 1, -> { Session.count } => 1` | one per expression | Strings are evaluated with `eval` in the **block's binding**, so they can use local variables visible to the block. Lambdas avoid string evaluation and read better when the expression has arguments. A message can be passed after the difference, or as the second argument with the hash form. ## A sign-up test In a meditation app built with the Rails 8 authentication generator plus a sign-up form, a successful sign-up creates the `User` and logs them in by creating a `Session` row: ```ruby class SignUpsTest < ActionDispatch::IntegrationTest test "signing up creates a user and a session" do assert_difference({ "User.count" => 1, "Session.count" => 1 }) do post sign_up_path, params: { user: { email_address: "[email protected]", password: "calm-breath-42" } } end assert_redirected_to root_path end test "an invalid sign-up creates nothing" do assert_no_difference ["User.count", "Session.count"] do post sign_up_path, params: { user: { email_address: "" } } end assert_response :unprocessable_content end end ``` ## Related assertions - `assert_no_difference(expression)` is the same check with a difference of 0; it accepts strings, lambdas and arrays. - `assert_changes(expression, from:, to:)` checks that a value changed, optionally from and to specific values, for anything that is not a count, such as a plan name or a timestamp. - `assert_no_changes(expression)` checks that a value did not change. `assert_difference` returns whatever the block returned, so a test can capture a created record or a response in the same statement. ## Reading the failure message When the check fails, the message names the expression and the change it actually saw, for example "`User.count` didn't change by 1, but by 0." A lambda is shown by its source, and on Minitest 6 the message also carries a diff of the expected and actual values. A custom message passed to the assertion is printed in front of that text. A failure therefore usually says which side effect was missing without a debugger: 0 means the block never created the row, 2 means something created it twice, perhaps a callback and the controller both. ## Choosing what to count - Count the **rows the feature promises**: users, sessions, bookings, subscriptions. - Count **scoped** where other rows may appear, such as `-> { user.sessions.count }`. - Count **nothing** on failure paths, with `assert_no_difference`, so invalid input cannot silently create half a record. ## Traps - **Counting the wrong thing.** `user.sessions.size` may read a loaded association without querying again; prefer `count`, or a lambda that reloads, so the second evaluation hits the database. - **Counting too broadly.** `"Session.count"` also counts sessions created by fixtures or callbacks you did not intend; a scoped count such as `-> { users(:mia).sessions.count }` is more precise when other rows may appear. - **Hiding a second effect.** A single expression passes even if the block also created an unexpected row elsewhere; the hash form makes every expected side effect explicit. - **Using it for side effects that are not rows.** Enqueued jobs and sent mail have their own helpers, such as `assert_enqueued_with` and `assert_emails`, which also check *which* job or mail. ## In RSpec rspec-rails exposes Minitest's own assertions to specs but not Active Support's `assert_difference`, so RSpec suites express the same check with RSpec's `change` matcher. The Rails assertion is the one an interviewer means by "assert_difference", and it is what the generated Minitest suite uses.
- Why can assert_difference "user.sessions.size" pass or fail misleadingly?`size` on an association that is already loaded counts the in-memory records without querying again, so the after-value may not reflect rows the request inserted. Use `count`, which always runs a `COUNT` query, or a lambda that reloads the user, so both evaluations read the database.
- When would you use assert_changes instead of assert_difference?When the side effect is a value rather than a number of rows: a status flipping from `trial` to `premium`, a timestamp being set, or a flag toggling. `assert_changes` takes `from:` and `to:` and compares values, while `assert_difference` only compares numeric results.
- assert_difference defaults to expecting no change
- assert_difference with an array lets each expression have its own difference
- String expressions are evaluated once, after the block
- assert_difference is only available in model tests