Skip to content

Commit 2fc5707

Browse files
committed
Issue warning when the error is a precision error
1 parent 6ca741f commit 2fc5707

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

lib/rspec/rails/matchers/active_job.rb

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,26 @@ def at_match?(job)
163163
return job[:at].nil? if @at == :no_wait
164164
return false unless job[:at]
165165

166-
values_match?(@at, Time.at(job[:at]))
166+
scheduled_at = Time.at(job[:at])
167+
values_match?(@at, scheduled_at) || check_for_inprecise_value(scheduled_at)
168+
end
169+
170+
def check_for_inprecise_value(scheduled_at)
171+
return unless Time === @at && values_match?(@at.change(usec: 0), scheduled_at)
172+
RSpec.warn_with (<<-WARNING).gsub(/^\s+\|/, '').chomp
173+
|[WARNING] Your expected `at(...)` value does not match the job scheduled_at value
174+
|unless microseconds are removed. This precision error often occurs when checking
175+
|values against `Time.current` / `Time.now` which have usec precision, but Rails
176+
|uses `n.seconds.from_now` internally which has a usec count of `0`.
177+
|
178+
|Use `change(usec: 0)` to correct these values.
179+
|
180+
|Note: RSpec cannot do this for you because jobs can be scheduled with usec
181+
|precision and we do not know wether it is on purpose or not.
182+
|
183+
|
184+
WARNING
185+
false
167186
end
168187

169188
def set_expected_number(relativity, count)

spec/rspec/rails/matchers/active_job_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,17 @@ def self.name; "LoggingJob"; end
233233
end
234234
end
235235

236+
it "warns when time offsets are inprecise" do
237+
expect(RSpec).to receive(:warn_with).with(/precision error/)
238+
239+
time = Time.current.change(usec: 550)
240+
travel_to time do
241+
expect {
242+
expect { hello_job.set(wait: 5).perform_later }.to have_enqueued_job.at(time + 5)
243+
}.to raise_error(/expected to enqueue exactly 1 jobs/)
244+
end
245+
end
246+
236247
it "accepts composable matchers as an at date" do
237248
future = 1.minute.from_now
238249
slightly_earlier = 58.seconds.from_now

0 commit comments

Comments
 (0)