Unexpected output when testing class method that raises an exception

5 views
Skip to first unread message

Jack Royal-Gordon

unread,
Aug 23, 2020, 6:35:50 PM8/23/20
to rs...@googlegroups.com
I’ve got a spec that is meant in part to test error handling within a public class method, and it stubs out a lower-level method that I don’t want to test in this instance. The partial spec looks like:

it 'reacts appropriately to an error from get_json' do
expect(described_class).to receive(:get_json).with("historical/#{@date.strftime('%F')}.json") \
.and_return(@invalid_rates)
expect(described_class.load_one_date(@date)).to raise_exception RuntimeError
end

The output from running the spec looks like:

1) CurrencyConversion.load_one_date(date, include_currencies=nil) reacts appropriately to an error from get_json
Failure/Error: expect(described_class.load_one_date(@date)).to raise_exception RuntimeError
RuntimeError:
Error from OpenExchangeRates when calling with date Sun, 23 Aug 2020: Invalid App ID provided - please sign up at https://openexchangerates.org/signup, or contact sup...@openexchangerates.org.
# ./app/models/currency_conversion.rb:100:in `load_one_date'
# ./spec/models/currency_conversion_spec.rb:133:in `block (3 levels) in <top (required)>’

So, I’m expecting a RuntimeError, I get a RuntimeError, and yet the spec fails. The referenced line in currency_conversion.rb is the “raise” command, and the referenced line in currency_conversion_spec.rb is the second “expect”. I tried a couple variations (change the first “expect” to “allow” and dropping the “RuntimeError” from the “raise_exception”, with no change to the behavior.

Phil Pirozhkov

unread,
Aug 24, 2020, 3:50:58 PM8/24/20
to Jack Royal-Gordon
You should be using block syntax if you expect a certain block of code to raise an exception.
```
expect { described_class.load_one_date(@date) }.to raise_exception RuntimeError
```

`raise_exception` is not really compatible with the value expectations, but there is no warning.
We are going to avoid that kind of mistakes in the next major release.

- Phil

--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/6BFF6A54-7F11-4028-B2EB-84759DF3ACE0%40pobox.com.

Jack Royal-Gordon

unread,
Aug 24, 2020, 8:13:08 PM8/24/20
to rs...@googlegroups.com
Of course, I can’t believe I forgot about that. I was messing around so much with stubbing methods that I didn’t notice that.

Reply all
Reply to author
Forward
0 new messages