Skip to content

Commit 1191bda

Browse files
morgothsebjacobs
authored andcommitted
Improve failure message for AJ matcher (rspec#1722)
1 parent d1c72f5 commit 1191bda

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

lib/rspec/rails/matchers/active_job.rb

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,14 @@ def thrice
6767
end
6868

6969
def failure_message
70-
"expected to enqueue #{base_message}"
70+
"expected to enqueue #{base_message}".tap do |msg|
71+
if @unmatching_jobs.any?
72+
msg << "\nQueued jobs:"
73+
@unmatching_jobs.each do |job|
74+
msg << "\n #{base_job_message(job)}"
75+
end
76+
end
77+
end
7178
end
7279

7380
def failure_message_when_negated
@@ -89,7 +96,7 @@ def supports_block_expectations?
8996
private
9097

9198
def check(jobs)
92-
@matching_jobs_count = jobs.count do |job|
99+
@matching_jobs, @unmatching_jobs = jobs.partition do |job|
93100
if serialized_attributes.all? { |key, value| value == job[key] }
94101
args = ::ActiveJob::Arguments.deserialize(job[:args])
95102
@block.call(*args)
@@ -98,6 +105,7 @@ def check(jobs)
98105
false
99106
end
100107
end
108+
@matching_jobs_count = @matching_jobs.size
101109

102110
case @expectation_type
103111
when :exactly then @expected_number == @matching_jobs_count
@@ -115,6 +123,17 @@ def base_message
115123
end
116124
end
117125

126+
def base_job_message(job)
127+
msg_parts = []
128+
msg_parts << "with #{::ActiveJob::Arguments.deserialize(job[:args])}" if job[:args].any?
129+
msg_parts << "on queue #{job[:queue]}" if job[:queue]
130+
msg_parts << "at #{Time.at(job[:at])}" if job[:at]
131+
132+
"#{job[:job].class.name} job".tap do |msg|
133+
msg << " #{msg_parts.join(', ')}" if msg_parts.any?
134+
end
135+
end
136+
118137
def serialized_attributes
119138
{}.tap do |attributes|
120139
attributes[:args] = ::ActiveJob::Arguments.serialize(@args) if @args.any?

spec/rspec/rails/matchers/active_job_spec.rb

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -211,11 +211,13 @@ def perform; end
211211

212212
it "generates failure message with all provided options" do
213213
date = Date.tomorrow.noon
214-
message = "expected to enqueue exactly 2 jobs, with [42], on queue low, at #{date}, but enqueued 0"
214+
message = "expected to enqueue exactly 2 jobs, with [42], on queue low, at #{date}, but enqueued 0" + \
215+
"\nQueued jobs:" + \
216+
"\n Class job with [1], on queue default"
215217

216218
expect {
217219
expect {
218-
hello_job.perform_later
220+
hello_job.perform_later(1)
219221
}.to have_enqueued_job(hello_job).with(42).on_queue("low").at(date).exactly(2).times
220222
}.to raise_error(message)
221223
end

0 commit comments

Comments
 (0)