Stubbing rspec and_raise and adding a message

1.9k views Asked by At

I'm writing tests which need to test the rescues in my code.

Model code:

rescue Coinbase::Error => e
  #debugger
  if e == "You don't have that many bitcoins in your account to sell."
  ...
end

Rspec code:

allow_any_instance_of(Order).to receive(:sell).and_raise(Coinbase::Error, "You don't have that many bitcoins in your account to sell.")

Adding the debugger where I did and looking at the value of e in console, I see

#<Coinbase::UnauthorizedError: Coinbase::UnauthorizedError>

So the message isn't being passed in.

I've been googling for this for the last 40 minutes and everything I've found only covers sending the error class in, not the message. Presumably there are situations where there are the same error class but different messages.

Any suggestions would be great. Thanks!

2

There are 2 answers

5
NateSHolland On

I think you want to do: Coinbase::Error.new("You don't have that many bitcoins in your account to sell.") inside the raise call.

Update, I think you also want e.message == "" not e == "" because you are comparing an error to a string not an error message.

0
HashNotAdam On

In situations where you are rescuing a custom error class, it is possible that the package does not conform to the standard Ruby interface for errors.

Normally, the first argument passed to an error is the message but, in errors that are not coming from the standard library, this might not be the case.

The Ferrum gem does this a lot. For example, when it raises a Ferrum::BrowserError, the first argument is a custom response hash that includes a "message" parameter so stubbing this is something like:

allow(ferrum_node).to receive(:focus).and_raise(
  Ferrum::BrowserError.new({ "message" => "Element is not focusable" })
)