Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec sequence of returned values AND raised errors from stub

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?

like image 640
Filip Bartuzi Avatar asked Jun 03 '16 08:06

Filip Bartuzi


People also ask

What is stub in RSpec?

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.

How do I mock a method in RSpec?

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.

What is allow in RSpec?

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.


1 Answers

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
like image 79
Matouš Borák Avatar answered Oct 14 '22 05:10

Matouš Borák