skip to content

A Rails 8.1 sign-up schedules TrialExpiryJob seven days out; how do you test that it is scheduled and that running it ends the trial at the right time?

level: seniorimportance: should knowfreq 32%

answer

  1. assert the schedule, then the effect
  2. at: matches within one second
  3. performing ignores the scheduled time
  4. the job must re-check the clock
  5. travel before perform_enqueued_jobs

basics

~20 s

Assert the schedule with assert_enqueued_with(job: TrialExpiryJob, at: 7.days.from_now) around the sign-up. The test adapter performs scheduled jobs immediately, so travel past the deadline, run perform_enqueued_jobs and assert the trial ended; running it early must change nothing.

solid answer

~50 s

Split it into two claims. First, scheduling: wrap the sign-up in `assert_enqueued_with(job: TrialExpiryJob, at: 7.days.from_now)`, matching `args:` with a lambda because the request creates the user; a time passed to `at:` matches within one second, which absorbs rounding, and `freeze_time` first makes it exact. Second, behaviour: `perform_enqueued_jobs` performs scheduled jobs right away, since the test adapter ignores the wait unless you pass `at:`, so performing alone proves nothing about timing. `travel 7.days + 1.minute`, then `perform_enqueued_jobs`, then assert `user.reload.trial_expired?`. Add the negative case: perform it at day six and assert the trial is still active, which forces the job to check `trial_ends_at` against `Time.current` rather than trusting the queue. If the job sends a "trial ended" email with `deliver_later`, the block form of `perform_enqueued_jobs` also runs that delivery job. In Rails 8.1 a job enqueued inside a transaction is not deferred to commit unless the job sets `enqueue_after_transaction_commit = true`.

code

ruby · 12 lines
ruby
test "expiry job only fires once the deadline has passed" do
  user = users(:mia)
  TrialExpiryJob.set(wait: 7.days).perform_later(user)

  travel 6.days
  perform_enqueued_jobs(at: Time.current)   # skips: scheduled later
  assert_equal "trial", user.reload.plan

  travel 2.days
  perform_enqueued_jobs(at: Time.current)   # now due
  assert_equal "expired", user.reload.plan
end

go deeper

for a junior

Assert the enqueued job with its class and time, and know that performing it in a test happens immediately.

for a middle

Combine travel with perform_enqueued_jobs to test the effect, and explain the at: tolerance in assert_enqueued_with.

for a senior

Separate scheduling from behaviour, add the early-run negative test, and make the job check the deadline itself so retries and backlogs stay correct.

for a principal

Set the team's approach to time-based jobs: idempotent, deadline-checking jobs and tests that prove timing and behaviour separately.

## Two separate claims "The trial ends after seven days" mixes two things a test can check independently: 1. **Scheduling:** signing up enqueues `TrialExpiryJob` for the right user, seven days out. 2. **Behaviour:** when the job runs after the deadline, the trial ends; when it runs early, nothing happens. Testing only the first misses a broken job. Testing only the second misses a missing or mistimed enqueue. A senior answer keeps them apart. ## Asserting the schedule ```ruby test "sign-up schedules trial expiry" do freeze_time assert_enqueued_with(job: TrialExpiryJob, at: 7.days.from_now) do post sign_up_path, params: { user: { email_address: "[email protected]", password: "calm-breath-42" } } end end ``` Details worth naming: - `at:` with a time is turned into a range of one second either side, so small differences between the time computed in the test and in the request do not fail the assertion. `freeze_time` makes both sides identical anyway. - `args:` can be added once the user exists, either as `[User.last]` after the block or as a lambda: `args: ->(args) { args.first.email_address == "[email protected]" }`. - The block form only considers jobs enqueued inside it, so jobs from fixtures or setup do not interfere. ## Asserting the behaviour The test adapter does not wait for a job's scheduled time. Both forms of `perform_enqueued_jobs` run scheduled jobs immediately unless `at:` is given. That means the job's own logic must decide whether the trial has ended: ```ruby class TrialExpiryJob < ApplicationJob def perform(user) return if user.trial_ends_at.future? user.update!(plan: "expired") end end ``` The tests then control the clock and run the job: ```ruby test "trial expires after seven days" do TrialExpiryJob.set(wait: 7.days).perform_later(users(:mia)) travel 7.days + 1.minute perform_enqueued_jobs assert_equal "expired", users(:mia).reload.plan end test "running early leaves the trial active" do TrialExpiryJob.set(wait: 7.days).perform_later(users(:mia)) travel 6.days perform_enqueued_jobs assert_equal "trial", users(:mia).reload.plan end ``` The negative test is the one that catches a job which trusts the queue's timing instead of checking `trial_ends_at`. That matters in production too: retries, a backlog or a job performed manually can run it at any time. ## Filtering by time instead `perform_enqueued_jobs(at: Time.current)` without a block runs only jobs scheduled at or before the given time. After `travel 8.days`, it would include the expiry job; at day six it would skip it. This tests the scheduling arithmetic but not the job's own guard, so it complements the negative test rather than replacing it. ## Follow-on jobs and mail If the job sends a "your trial has ended" email with `deliver_later`: - the block form, `perform_enqueued_jobs { ... }`, performs jobs as they are enqueued, including the mail delivery job the expiry job enqueues; - `assert_enqueued_email_with TrialMailer, :ended` after the block-less `perform_enqueued_jobs` checks that the email was queued without delivering it. ## Transactions in Rails 8.1 In Rails 8.1, a job enqueued inside a database transaction is handed to the adapter immediately unless the job class sets `enqueue_after_transaction_commit = true`; the class attribute defaults to false, and the adapter's own preference is ignored. A job that opts in reaches the adapter only once the surrounding transactions commit. Keep the setting explicit on the job class, so readers of both the test and the production code know when the job becomes visible. ## Versions of this test that pass for the wrong reason - Performing the job right after enqueueing and asserting the trial expired: it only passes if the job ignores the deadline, which is the bug the test should catch. - Asserting only `assert_enqueued_jobs 1`: any job satisfies it, and the time is never checked. - Travelling forward but computing the expected deadline after the travel, so the expected and actual values move together. - Comparing `at:` against a time read before the request without freezing, then relying on luck; the one-second tolerance hides most of this, but freezing makes it deterministic. ## Checklist - Freeze or control time before asserting `at:`. - Assert the enqueue with class, arguments and time. - Travel past the deadline, perform, assert the effect. - Travel short of it, perform, assert no effect. - Let `after_teardown` undo the time travel; do not rely on test order.

  • Why does assert_enqueued_with(at: 7.days.from_now) pass even if the request computed the time a few milliseconds earlier?
    When `at:` is a time, the helper turns it into a matcher covering one second before and after. Small gaps between the test's and the request's clock reads fall inside that window. Freezing time first removes the gap entirely and makes the intent clearer.
  • Why is a negative test that performs the job early important?
    The test adapter performs scheduled jobs immediately, and production can also run a job early through retries or manual runs. Only a test that performs the job before the deadline and expects no change proves the job checks `trial_ends_at` against the current time.

  • perform_enqueued_jobs waits until a scheduled job's time has come
  • Asserting the enqueue proves the trial actually ends
  • assert_enqueued_with(at:) needs the exact microsecond to match
  • In Rails 8.1, jobs enqueued in a transaction wait for commit by default
  • The job can rely on the queue delay instead of checking trial_ends_at

Assumes Rails 8.1, where jobs enqueued inside a transaction are not deferred to commit unless the job sets enqueue_after_transaction_commit = true (the default is false).