5

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!

Zack Shapiro
  • 6,648
  • 17
  • 83
  • 151

2 Answers2

2

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.

NateSHolland
  • 1,130
  • 2
  • 11
  • 25
  • open up console and try running Coinbase::Error.new("You don't have that many bitcoins in your account to sell."), what happens? – NateSHolland Nov 11 '14 at 06:09
  • That works fine. `allow_any_instance_of(Order).to receive(:sell).and_raise(Coinbase::Error.new("You don't have that many bitcoins in your account to sell."))` does not for some odd reason. I can't get `e` to show the message when I place the debugger where it is above, I get the error I mentioned before – Zack Shapiro Nov 11 '14 at 06:10
  • Try the update I added, do both of those changes and see if they work – NateSHolland Nov 11 '14 at 06:11
  • Just did. `e.message` in the test is giving me `"Coinbase::UnauthorizedError"`, full print out of `e` is `#` – Zack Shapiro Nov 11 '14 at 06:12
  • 1
    So in console try doing `e =Coinbase::Error.new("You don't have that many bitcoins in your account to sell."` and then `e.message` you should get the message you are looking for back. And also what does just doing `e` print? – NateSHolland Nov 11 '14 at 07:00
0

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" })
)