skip to content

In rspec-rails, how do the have_enqueued_job and have_been_enqueued matchers differ, and what must the Active Job adapter be for either to work?

level: middleimportance: should knowfreq 44%

answer

  1. block form vs value form
  2. diff of enqueued_jobs around the block
  3. exactly once unless you chain a count
  4. ActiveJob::Base.queue_adapter = :test
  5. with, on_queue, at(:no_wait)

basics

~20 s

have_enqueued_job is a block matcher counting jobs enqueued inside expect { }; have_been_enqueued checks a job class against everything the adapter holds. Both raise unless ActiveJob::Base.queue_adapter is the test adapter, which a Rails test environment uses when nothing else is configured.

solid answer

~40 s

`have_enqueued_job` (alias `enqueue_job`) only accepts a block: it snapshots the test adapter's `enqueued_jobs`, runs the block and matches against the jobs added, so `expect { post "/timesheets/4/submit" }.to have_enqueued_job(TimesheetApprovalJob).with(timesheet)` ignores earlier noise. `have_been_enqueued` is the value form, `expect(TimesheetApprovalJob).to have_been_enqueued`, and reads every job the adapter holds, so leftovers count unless they are cleared. Both default to exactly one match and chain `with`, `on_queue`, `at`, `at_priority` and counts like `twice` or `at_least(2).times`. Both call a guard that raises unless `ActiveJob::Base.queue_adapter` is a `TestAdapter`. Rails falls back to `:test` in the test environment when no adapter is configured; since Rails 7.2 an explicit `config.active_job.queue_adapter` is respected in tests, so setting it in `config/application.rb` breaks the matchers.

code

ruby · 14 lines
ruby
# Value form: reads everything the adapter holds
RSpec.describe Timesheet, type: :model do
  before { ActiveJob::Base.queue_adapter.enqueued_jobs.clear }

  it "queues a reminder when left in draft" do
    timesheets(:week_40).remind_later
    expect(TimesheetReminderJob).to have_been_enqueued
      .with(timesheets(:week_40))
      .at(Date.tomorrow.noon)
  end
end

# config/application.rb -- breaks the matchers in tests since Rails 7.2
# config.active_job.queue_adapter = :solid_queue

go deeper

for a junior

Write expect { action }.to have_enqueued_job(SomeJob) and know it needs the test queue adapter.

for a middle

Explain the block-versus-value difference, the default of exactly once, and the with, on_queue and at chains, including argument serialization.

for a senior

Diagnose a matcher that raises about the adapter after a config change, and a value-form expectation that passes because of jobs left over from setup.

for a principal

Decide how much of a job pipeline a suite proves by enqueue assertions versus performing jobs, given the cost of false confidence when only enqueueing is checked.

## Two matchers, two shapes rspec-rails ships a family of Active Job matchers in `RSpec::Rails::Matchers`. The two that interviewers ask about differ in what they look at: | Matcher | Form | Looks at | Typical use | |---|---|---|---| | `have_enqueued_job(Job)` (alias `enqueue_job`) | block: `expect { ... }.to` | jobs added to the adapter while the block ran | the action under test enqueues the job | | `have_been_enqueued` | value: `expect(Job).to` | every job the adapter currently holds | after-the-fact check in a job or model spec | | `have_performed_job(Job)` (alias `perform_job`) | block | jobs performed while the block ran | with `perform_enqueued_jobs` | | `have_been_performed` | value | every job the adapter has performed | adapter set to perform jobs | `have_enqueued_job` raises `ArgumentError` if it is given a value instead of a block. It copies the adapter's `enqueued_jobs` before calling the block, copies it again afterwards and matches only the difference. `have_been_enqueued` takes the job class as the actual value and scans the whole list, which is why its own documentation shows `before { ActiveJob::Base.queue_adapter.enqueued_jobs.clear }`. ## Constraints you can chain Both matchers start as "exactly once" and narrow with chained constraints: - `with(*args)` matches the job's arguments after a serialize and deserialize round trip, so a model passed in goes out as a GlobalID and is loaded back before the comparison; a block form `with { |a, b| ... }` allows custom checks. - `on_queue("approvals")` checks the queue name as a string. - `at(time)` checks `scheduled_at`; `at(:no_wait)` asserts there was no delay. - `at_priority(n)` checks the priority. - `exactly(n)`, `at_least(n)`, `at_most(n)`, with `once`, `twice`, `thrice` and `times` for readability. Two details catch people out: 1. `at(Time.current + 1.hour)` can miss the scheduled time by microseconds. When the values match once microseconds are dropped, rspec-rails prints a warning suggesting `change(usec: 0)`. 2. When rspec-mocks has `verify_partial_doubles` switched on, the matcher also checks the enqueued arguments against `perform`'s signature and fails with "Incorrect arguments passed to" the job class when they do not fit. ## The adapter requirement Every one of these matchers first calls a guard that checks `ActiveJob::QueueAdapters::TestAdapter === ActiveJob::Base.queue_adapter`. If the check fails, it raises `StandardError` with the message "To use ActiveJob matchers set `ActiveJob::Base.queue_adapter = :test`". How a Rails 8.1 app ends up with the right adapter: - Active Job's railtie sets `queue_adapter ||= (Rails.env.test? ? :test : :async)`, so a test environment with no configuration gets the test adapter. - `solid_queue:install` writes `config.active_job.queue_adapter = :solid_queue` into `config/environments/production.rb` only, which leaves tests alone. - Since Rails 7.2, tests respect an explicitly configured adapter. If someone moves `queue_adapter = :solid_queue` into `config/application.rb`, it applies to the test environment too and the matchers raise. Set `:test` in `config/environments/test.rb`, or keep the production setting where the installer put it. ## A request spec for a time-sheet submission ```ruby RSpec.describe "Timesheet submission", type: :request do it "queues the approval job" do timesheet = timesheets(:week_40) expect { post "/timesheets/#{timesheet.id}/submission", as: :json }.to have_enqueued_job(TimesheetApprovalJob) .with(timesheet) .on_queue("approvals") end end ``` The block form keeps the assertion local to the request: a job enqueued by fixture setup or an earlier example cannot satisfy or spoil it. ## Mail delivered later `deliver_later` enqueues a mail delivery job, so the same family covers it with `have_enqueued_mail(TimesheetMailer, :submitted)`, which also chains `with`, `on_queue`, `at` and counts. Checking the rendered mail itself is a mailer spec's job. ## Negative expectations `expect { ... }.not_to have_enqueued_job(TimesheetApprovalJob)` is supported. For the negated block form the matcher switches its count to "at least once" before inverting, so the expectation fails if the block enqueues one or more matching jobs, not only exactly one. That makes `not_to` a reliable guard against an action that should stay silent, for example rejecting a timesheet that was already approved. ## Picking the right one - Testing that an **action** enqueues work: the block form, so the assertion is scoped to that action. - Testing **scheduling details**: chain `at`, `on_queue` and `at_priority` on the block form. - Testing that a job **ran** and had effects: perform it, either with `perform_enqueued_jobs` in the spec or by calling the job directly, and assert on the result rather than only on the enqueue.

  • Why does expect(TimesheetApprovalJob).to have_enqueued_job raise an ArgumentError?
    `have_enqueued_job` only supports block expectations: it needs to run code between two snapshots of the adapter's `enqueued_jobs`. Passing the class as a value gives it nothing to run. Use `expect { ... }.to have_enqueued_job(TimesheetApprovalJob)`, or switch to the value matcher `have_been_enqueued`.
  • How do you assert that a job was enqueued with no delay?
    Chain `at(:no_wait)`. The matcher then requires the job's scheduled time to be empty, so a job set with `wait:` or `wait_until:` fails the expectation, which is useful when an action must enqueue immediately.

  • have_enqueued_job accepts a job class as a value, not only a block
  • have_been_enqueued only counts jobs from the current example
  • Setting queue_adapter = :solid_queue in application.rb leaves tests on the test adapter
  • The matchers default to at least once rather than exactly once
  • on_queue compares symbols, so on_queue("approvals") never matches