Skip to content

Commit

Permalink
Fixup have_enqueued_job matcher on job retries
Browse files Browse the repository at this point in the history
Previously we were checking only job counts, so if one job was
performed and one job was added - matcher failed. Check by unique
id (`#hash`) instead.
We cannot use `job['job_id']` here, because job retains `job_id` on retry.
  • Loading branch information
ojab committed Feb 14, 2022
1 parent 620a869 commit f6316ca
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Expand Up @@ -5,6 +5,7 @@ on:
- 'main'
- '*-maintenance'
- '*-dev'
- '*'
pull_request:
branches:
- '*'
Expand Down
6 changes: 4 additions & 2 deletions lib/rspec/rails/matchers/active_job.rb
Expand Up @@ -230,9 +230,11 @@ def initialize(job)
def matches?(proc)
raise ArgumentError, "have_enqueued_job and enqueue_job only support block expectations" unless Proc === proc

original_enqueued_jobs_count = queue_adapter.enqueued_jobs.count
original_enqueued_jobs_hashes = queue_adapter.enqueued_jobs.map(&:hash)
proc.call
in_block_jobs = queue_adapter.enqueued_jobs.drop(original_enqueued_jobs_count)
in_block_jobs = queue_adapter.enqueued_jobs.reject do |job|
original_enqueued_jobs_hashes.include?(job.hash)
end

check(in_block_jobs)
end
Expand Down
25 changes: 25 additions & 0 deletions spec/rspec/rails/matchers/active_job_spec.rb
Expand Up @@ -98,6 +98,31 @@ def self.name; "LoggingJob"; end
expect { }.not_to have_enqueued_job
end

context "when job is retried" do
include ActiveJob::TestHelper

let(:retried_job) do
Class.new(ActiveJob::Base) do
retry_on StandardError, queue: :retry

def self.name; "RetriedJob"; end
def perform; raise StandardError; end
end
end

before { stub_const("RetriedJob", retried_job) }

it "passes with reenqueued job" do
retried_job.perform_later

time = Time.current.change(usec: 0)
travel_to time do
expect { perform_enqueued_jobs(queue: :default) }
.to have_enqueued_job(retried_job).on_queue(:retry).at(time + 3)
end
end
end

it "fails when job is not enqueued" do
expect {
expect { }.to have_enqueued_job
Expand Down

0 comments on commit f6316ca

Please sign in to comment.