Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec: Show a model's errors when it's not valid

I generally write something like this in my Rspec tests:

user.new(...)
user.should be_valid

The problem is, when that test fails, I don't get to see the errors on the user object. Is there a nice way to re-write this test so that in the Rspec output I'll see something like user.errors.inspect? I've tried user.errors.should be_empty, but that still just says "expected true, got false."

like image 700
Paul A Jungwirth Avatar asked Jan 19 '23 02:01

Paul A Jungwirth


1 Answers

You can do this by defining a custom matcher. Something like this should do the trick.

RSpec::Matchers.define :be_valid do
  match do |actual|
    actual.valid?
  end

  failure_message_for_should do |actual|
    "expected that #{actual} would be valid (errors: #{actual.errors.full_messages.inspect})"
  end

  failure_message_for_should_not do |actual|
    "expected that #{actual} would not be valid"
  end

  description do
    "be valid"
  end
end
like image 66
hammar Avatar answered Jan 29 '23 11:01

hammar