Testing Jobs and Cables

Rails provides minimal support for testing ActiveJob background jobs and ActiveCable web sockets.

In RSpec a spec of type: :job or one placed in the spec/jobs directory exposes a couple of matchers. Before you run job specs, you need to specify that the jobs queue is using the test setting and not running off to Sidekiq or whatever. You do that with ActiveJob::Base.queue_adapter = :test, which you can use in a before block.

The basic matcher is have_been_enqueued, and the argument to it is the class of the job being enqueued, as in

 it ​"should enqueue a mailer job"​ ​do
  AddsTaskWorkflow.new.run
  expect(TaskAddedMailJob).to have_been_enqueued
 end

You can chain a lot of things to have_been_enqueued for more specific ...

Get Rails 5 Test Prescriptions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.