Skip to content

Instantly share code, notes, and snippets.

@mrnugget
Last active March 3, 2016 05:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrnugget/348d7b7c9cde658c3139 to your computer and use it in GitHub Desktop.
Save mrnugget/348d7b7c9cde658c3139 to your computer and use it in GitHub Desktop.
How do I expect to receive a message (maybe multiple times) and the arguments I specified have to be provided once?
class MyWorker
def self.perform_at(timestamp, job_name)
end
end
describe 'expecting multiple calls to same method' do
it 'works if only one call is made to the method' do
time_now = Time.now
expect(MyWorker).to receive(:perform_at).with(time_now, 'dowork')
MyWorker.perform_at(time_now, 'dowork')
end
it 'does not work if we have multiple method calls we want to ignore' do
time_now = Time.now
expect(MyWorker).to receive(:perform_at).with(time_now, 'dowork')
MyWorker.perform_at(time_now, 'dowork')
MyWorker.perform_at(time_now + 60 * 60, 'dowork')
end
end
% bundle exec rspec expect_to_receive_spec.rb
.F
Failures:
1) expecting multiple calls to same method does not work if we have multiple method calls we want to ignore
Failure/Error: MyWorker.perform_at(time_now + 60 * 60, 'dowork')
#<MyWorker (class)> received :perform_at with unexpected arguments
expected: (2016-02-02 10:33:39.605657000 +0100, "dowork")
got: (2016-02-02 11:33:39.605657000 +0100, "dowork")
Diff:
@@ -1,2 +1,2 @@
-[2016-02-02 10:33:39.605657000 +0100, "dowork"]
+[2016-02-02 11:33:39.605657000 +0100, "dowork"]
# ./expect_to_receive_spec.rb:21:in `block (2 levels) in <top (required)>'
Finished in 0.0224 seconds (files took 0.0785 seconds to load)
2 examples, 1 failure
Failed examples:
rspec ./expect_to_receive_spec.rb:15 # expecting multiple calls to same method does not work if we have multiple method calls we want to ignore
@mrnugget
Copy link
Author

mrnugget commented Feb 2, 2016

This fixes it:

  it 'does not work if we have multiple method calls we want to ignore' do
    time_now = Time.now

    # Here is the fix:
    allow(MyWorker).to receive(:perform_at)

    expect(MyWorker).to receive(:perform_at).with(time_now, 'dowork').once

    # The order of these calls is random
    MyWorker.perform_at(time_now + 2 * 60 * 60, 'dowork')
    MyWorker.perform_at(time_now, 'dowork')
    MyWorker.perform_at(time_now + 1 * 60 * 60, 'dowork')
  end

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