Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example ActiveJob with RSpec Tests
class MyJob < ActiveJob::Base
queue_as :urgent
rescue_from(NoResultsError) do
retry_job wait: 5.minutes, queue: :default
end
def perform(*args)
MyService.call(*args)
end
end
require 'rails_helper'
RSpec.describe MyJob, type: :job do
include ActiveJob::TestHelper
subject(:job) { described_class.perform_later(123) }
it 'queues the job' do
expect { job }
.to change(ActiveJob::Base.queue_adapter.enqueued_jobs, :size).by(1)
end
it 'is in urgent queue' do
expect(MyJob.new.queue_name).to eq('urgent')
end
it 'executes perform' do
expect(MyService).to receive(:call).with(123)
perform_enqueued_jobs { job }
end
it 'handles no results error' do
allow(MyService).to receive(:call).and_raise(NoResultsError)
perform_enqueued_jobs do
expect_any_instance_of(MyJob)
.to receive(:retry_job).with(wait: 10.minutes, queue: :default)
job
end
end
after do
clear_enqueued_jobs
clear_performed_jobs
end
end
# As of RSpec 3.4.0 we now have #have_enqueued_job
# https://www.relishapp.com/rspec/rspec-rails/v/3-5/docs/matchers/have-enqueued-job-matcher
RSpec.describe MyJob, type: :job do
subject(:job) { described_class.perform_later(key) }
let(:key) { 123 }
it 'queues the job' do
expect { job }.to have_enqueued_job(described_class)
.with(key)
.on_queue("urgent")
end
end
@ChuckJHardy

This comment has been minimized.

@ChuckJHardy

This comment has been minimized.

Copy link
Owner Author

@ChuckJHardy ChuckJHardy commented Mar 11, 2017

Updated to include RSpec 3.4.0 #have_enqueued_job

@ollie314

This comment has been minimized.

Copy link

@ollie314 ollie314 commented Aug 8, 2017

👍

@jingz

This comment has been minimized.

Copy link

@jingz jingz commented Sep 6, 2017

👍

@fitchMitch

This comment has been minimized.

Copy link

@fitchMitch fitchMitch commented Dec 22, 2018

👍

@wiskarindra

This comment has been minimized.

Copy link

@wiskarindra wiskarindra commented Jan 21, 2020

👍

@kaka-ruto

This comment has been minimized.

Copy link

@kaka-ruto kaka-ruto commented Mar 17, 2021

👍

@gogvale

This comment has been minimized.

Copy link

@gogvale gogvale commented Sep 7, 2021

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment