Testing ActiveJob with RSpec

July 13, 2015

I recently found myself experimenting with ActiveJob, which provides a standard interface for various queueing backends. As is the Rails Way™, the documentation doesn't mention how to test jobs through RSpec, so I had to discover that for myself!

ActiveJob Basics

Jobs live in app/jobs and look like this:

# app/jobs/example_job.rb
class ExampleJob < ActiveJob::Base
  queue_as :default

  def perform(parameters)
    # do processing
  end
end

For these examples, I'm using DelayedJob, which stores everything in the application's database. But the job code is exactly the same, no matter what background processor you use.

We can add jobs to the queue, by calling

ExampleJob.perform_later(parameters)

Note, this only adds the job to the queue. In order to process the jobs, you need to keep a rake task running:

rake jobs:work

I'd usually add this to my Procfile, so that I can export it as an Ubuntu upstart process.

Testing

After a little digging, I discovered that testing ActiveJob is really straightforward:

# spec/jobs/example_job_spec.rb
require "rails_helper"

describe ExampleJob do
  describe "#perform" do
    it "does some example work" do
      expect{ ExampleJob.perform_now(parameters) }.to ...
    end
  end
end

The important call there is perform_now which runs the job directly, instead of queueing it.

You can see a fuller example in my Gatwick project.