When writing a spec that checks for raise_error
, you must use the block-syntax {}
for expect
:
expect { my_method(p1, p2, p3, p4, bad5) }.to raise_error(ArgumentError)
There is a much more in-depth explanation in this question's answers, but you asked for an explanation so I'll give you an abbreviated one:
Most rspec matchers are value matchers. That means that something like this:
expect(some_method).to eq(value)
is really saying:
perform some_method
and get its return value, then compare its return value to value
, and judge the success or failure of this spec on that comparison
When you're trying to test some piece of code that has a side effect, like possibly raising an exception, rspec needs to receive a block of code to run. It's a bit more like:
expect { <some block of code> }.to raise_error(ArgumentError)
perform <some block of code>
, and then compare what happens when that code is executed to what is expected to happen, and judge the success or failure of this spec on that comparison
This answer for the above-linked question goes into detail about when you need to use expect {}
and when you need to use expect()
.