Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: How to expect a method only on the third invocation #1114

Closed
joelpresence opened this issue Aug 19, 2016 · 1 comment
Closed

Question: How to expect a method only on the third invocation #1114

joelpresence opened this issue Aug 19, 2016 · 1 comment

Comments

@joelpresence
Copy link

Hi,

Suppose I have a test where I want some method foo to do its normal thing the first two times it is called (i.e. no mock interference) but raise an exception the third time it is called. How do I do this with rspec?

The context is something like the following:

# In some class

def bar
  foo "first invocation should succeed"
  ...
  foo "second invocation should succeed"
  ...
  foo "third invocation should raise an exception"
end

So how do I tell rspec to "leave foo alone and not override it for the first two invocations" but then "raise an exception for the third invocation using an expectation"?

I know that I can test foo separately, but I am trying to test some complex interactions here and I am unable to force method foo to raise an exception naturally (e.g. if it depends on a third party service) so I need to force it to raise an exception during the third call using an rspec expectation.

But the problem is that setting an rspec expectation overrides the method/stubs it for all three, whereas I just want the last.

Thanks! :-)

@JonRowe
Copy link
Member

JonRowe commented Aug 24, 2016

You can configure your own response logic however you want like so:

n = 0
expect(foo).to receive(:bar) do
  raise if n > 2
  n += 1
end

@JonRowe JonRowe closed this as completed Aug 24, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants