Displaying error messages in RSpec failures

April 23, 2008

The suggested way of checking if an ActiveRecord model has errors with RSpec is:

@something.errors.should be_empty  

When that fails, you get a report that says:

expected empty? to return true, got false

That's not very helpful because it doesn't tell you what the errors are. If you do this:

@something.errors.full_messages.should == []      

You get a more informative failure message:

expected: [],
got: ["Whatever can't be blank"] (using ==)

Posted in Technology | Tags RSpec, Ruby, Rails

Comments

1.

Or you could use my ValidationSpecHelper module, which could be called like so:


@it.should accept("blah").for(:firstname)
@it.should accept(:firstname).of("foobar")
@it.should reject(:firstname).of("")
@it.should reject(:firstname).of("chunky").with("reason")

and return failure messages like so:


expected validation to accept "" for firstname
but firstname had the following errors:
- firstname: can't be blank

expected validation to reject "a name" for firstname
but firstname was valid

and so on...

http://svn.ekenosen.net/public/rspec_validation_matcher/

There are other validation spec matchers out there, but I like mine the best. ;-)

# Posted By nicholas a. evans on Thursday, April 24 2008 at 1:39 PM

2.

Oh well, I guess the

 tags didn't work.  Preview buttons are nice things for blog comments.  ;-)

# Posted By nicholas a. evans on Thursday, April 24 2008 at 1:40 PM

3.

Or you just give up on rspec and its spaghetti mess of code and start using shoulda.

should_not_allow_values_for :email, "blah", "b lah"
should_allow_values_for :email, "a@b.com", "asdf@asdf.com"

# Posted By bryanl on Friday, April 25 2008 at 6:58 AM

Comments Disabled