I want to stub first two calls to HTTParty with raised exception and then, the third call, should return value.
before do
allow(HTTParty).to receive(:get).exactly(2).times.with(url).and_raise(HTTParty::Error)
allow(HTTParty).to receive(:get).with(url).and_return('{}')
end
but one allow override another one. how to set stub to raise errors for first few tries and then let it return a value?
In RSpec, a stub is often called a Method Stub, it's a special type of method that “stands in” for an existing method, or for a method that doesn't even exist yet.
Mocking with RSpec is done with the rspec-mocks gem. If you have rspec as a dependency in your Gemfile , you already have rspec-mocks available.
Use the allow method with the receive matcher on a test double or a real. object to tell the object to return a value (or values) in response to a given. message. Nothing happens if the message is never received.
According to info provided in this github issue, you can also do that with the following pure-RSpec approach. It leverages the most general way of defining mock responses using block:
before do
reponse_values = [:raise, :raise, '{}']
allow(HTTParty).to receive(:get).exactly(3).times.with(url) do
v = response_values.shift
v == :raise ? raise(HTTParty::Error) : v
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With