Skip to content

Commit

Permalink
Merge pull request #2573 from ojab/fixup_have_enqueued_job_on_retries
Browse files Browse the repository at this point in the history
Fixup `have_enqueued_job` matcher on job retries
  • Loading branch information
pirj committed Apr 28, 2023
2 parents 0c54f93 + 47f15d2 commit f598b53
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
2 changes: 2 additions & 0 deletions Changelog.md
Expand Up @@ -11,6 +11,8 @@ Bug Fixes:
(Eugene Kenny, Iliana, #2631)
* Support Rails 7.1's `#fixtures_paths` in example groups (removes a deprecation warning).
(Nicholas Simmons, #2664)
* Fix `have_enqueued_job` to properly detect enqueued jobs when other jobs were
performed inside the expectation block. (Slava Kardakov, Phil Pirozhkov, #2573)

### 6.0.1 / 2022-10-18
[Full Changelog](https://github.com/rspec/rspec-rails/compare/v6.0.0...v6.0.1)
Expand Down
6 changes: 3 additions & 3 deletions lib/rspec/rails/matchers/active_job.rb
Expand Up @@ -230,11 +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 = Set.new(queue_adapter.enqueued_jobs)
proc.call
in_block_jobs = queue_adapter.enqueued_jobs.drop(original_enqueued_jobs_count)
enqueued_jobs = Set.new(queue_adapter.enqueued_jobs)

check(in_block_jobs)
check(enqueued_jobs - original_enqueued_jobs)
end

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

context "when previously enqueued jobs were performed" do
include ActiveJob::TestHelper

before { stub_const("HeavyLiftingJob", heavy_lifting_job) }

it "counts newly enqueued jobs" do
heavy_lifting_job.perform_later
expect {
perform_enqueued_jobs
hello_job.perform_later
}.to have_enqueued_job(hello_job)
end
end

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

let(:unreliable_job) do
Class.new(ActiveJob::Base) do
retry_on StandardError, wait: 5, queue: :retry

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

before { stub_const("UnreliableJob", unreliable_job) }

it "passes with reenqueued job" do
time = Time.current.change(usec: 0)
travel_to time do
UnreliableJob.perform_later
expect { perform_enqueued_jobs }.to have_enqueued_job(UnreliableJob).on_queue(:retry).at(time + 5)
end
end
end

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

0 comments on commit f598b53

Please sign in to comment.