Today I Learned

A Hashrocket project

Ready to join Hashrocket? Find Openings here and apply today.

Delayed Job Queue Adapter in RSpec with Rails 5.1

In old versions of Rails, you were able to override the ActiveJob queue in a test like this:

describe MyJob do
  it 'works' do
    ActiveJob::Base.queue_adapter = :delayed_job
    expect {
      MyJob.perform_later(some_params)
    }.to change(Delayed::Job.count).by(1)
  end
end

With Rails 5.1, we have the ActiveJob::TestHelper class which you will need to employ in your tests. In order to override the queue a different strategy is needed.

describe MyJob do
  def queue_adapter_for_test
    ActiveJob::QueueAdapters::DelayedJobAdapter.new
  end
  
  it 'works' do
    expect {
      MyJob.perform_later(some_params)
    }.to change(Delayed::Job.count).by(1)
  end
end

You will need to add the following to your rspec config or a support file:

RSpec.configure do |config|
  config.include(ActiveJob::TestHelper)
end

# you will also need the code below for the test
# to clear out the jobs between test runs
class ActiveJob::QueueAdapters::DelayedJobAdapter
  class EnqueuedJobs
    def clear
      Delayed::Job.where(failed_at:nil).map &:destroy
    end
  end
  
  class PerformedJobs
    def clear
      Delayed::Job.where.not(failed_at:nil).map &:destroy
    end
  end
  
  def enqueued_jobs
    EnqueuedJobs.new
  end
  
  def performed_jobs
    PerformedJobs.new
  end
end
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.