Allowing multiple calls to the same method

5,764 views
Skip to first unread message

Aaric Pittman

unread,
Feb 11, 2021, 12:28:28 PM2/11/21
to rspec
I've got an instance double of a class and I want to stub two calls to the same method and return different values based on different arguments. This is an example of what I have.

allow(client_mock).to receive(:get_opportunity).with("1234567890").and_return(opportunity1)
allow(client_mock).to receive(:get_opportunity).with("0987654321").and_return(opportunity2)

I am getting the following error though

#<InstanceDouble(Client) (anonymous)> received :get_opportunity with unexpected arguments
expected: ("1234567890")
got: ("0987654321")
Please stub a default value first if message might be received with other args as well.

I feel like I've done this before without problems. Could someone tell me what I'm doing wrong?

Jack Royal-Gordon

unread,
Feb 11, 2021, 1:11:16 PM2/11/21
to rs...@googlegroups.com
The technique I would use is as follows:

allow(client_mock).to_receive(:get_opportunity) do |arg|
  case arg 
  when “1234567890
    opportunity1
  when “0987654321
    opportunity2
  end
end


Cheers!

--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/74a89ab9-4d86-4ddf-913d-42b928ecbac9n%40googlegroups.com.

Phil Pirozhkov

unread,
Feb 11, 2021, 1:54:02 PM2/11/21
to Jack Royal-Gordon
Aaric,

I might be missing something, but the following:

```
RSpec.describe 'A' do
it do
opportunity1 = 1
opportunity2 = 2

client_mock = double

allow(client_mock).to
receive(:get_opportunity).with("1234567890").and_return(opportunity1)
allow(client_mock).to
receive(:get_opportunity).with("0987654321").and_return(opportunity2)

expect(client_mock.get_opportunity("1234567890")).to eq 1
expect(client_mock.get_opportunity("0987654321")).to eq 2
end
end
```
passes just fine.
Even if you swap the call order.
Even if you call `get_opportunity` several times with the same argument.

How do you define `client_mock` exactly?

- Phil

Aaric Pittman

unread,
Feb 11, 2021, 3:18:24 PM2/11/21
to rspec
Thanks for the replys. 

It end up being user error. I was passing the wrong argument when initializing my test subject.

- Aaric

Reply all
Reply to author
Forward
0 new messages