[rspec-users] raise_error suggestion

Pat Maddox mailinglists at patmaddox.com
Wed Apr 14 16:42:16 EDT 2010


On Apr 14, 2010, at 12:28 PM, rogerdpack wrote:

> I remember reading a post where somebody mentioned something like
> 
> "sometimes after a refactoring, a test block like
> 
>     lambda { ... }.should raise_error
> 
> catches a NoMethodError in error, thus is actually failing, but the
> user isn't notified of the same."
> 
> A suggestion in this regard:
> change it so that if raise_error is called without parameters, and it
> catches NoMethodError, it outputs a warning somehow.
> 
> The objection to this might be "what if I *expect* a NoMethodError--
> I'll get spurious warnings"
> 
> Answer: user can, at that point, put in NoMethodError as a parameter,
> and warning goes away (and that's a rare enough case that it probably
> won't cause conflicts).

Be explicit about the error you expect to get:

lambda { ... }.should raise_error(SomeErrorClass, /match the message/)

Read the documentation at http://rspec.rubyforge.org/rspec/1.3.0/classes/Spec/Matchers.html#M000184

Nothing kills me more than a generic raise_error.  Especially when the block is wrapped around a whole bunch of code that doesn't need it e.g.

lambda {
  some_setup
  some_setup
  some.stupid_typo_that_blows_up
  call_that_we_expect_to_raise_an_error
}.should raise_error

Anyone on my team using a naked raise_error matcher gets a smack on the head from me...and I have a special spiky dunce cap for whoever does the above example.

Also note in RSpec 1.3.0 #lambda is aliased to #expect, and #should to #to, so you can do

expect { ... }.to raise_error(SomeErrorClass, /match the message/)

which you may find more pleasant to read.

Pat


More information about the rspec-users mailing list