views:

86

answers:

2

I am trying to return more informative failure messages from an expectation. I have a helper method that iterates a hash, testing for mass assignment protection on a model. If the expectation fails I would like to output which attribute failed. I have come across failure_message_for_should, but I am not sure how to properly use it.

Thanks!

A: 

failure_message_for_should isn't a matcher, it's a method you overwrite if you're writing your own custom matcher. I don't think it does what you're looking for.

BJ Clark
+1  A: 

Just write a simple matcher really and you can kind of specify your own messages then. Have a look at this code:

def be_even
 simple_matcher("an even number") { |given| given % 2 == 0 }
end

describe 2 do
 it "should be even" do
  3.should be_even
 end
end

Put this code in a file called so_spec.rb and run it like this:

spec so_spec.rb -f n -c

This will give you the following output:

'2 should be even' FAILED
expected "an even number" but got 3

and you can easily see that "an even number" is really the custom message and is more informative than expected true got false. This is one approach. However, rspec is quite flexible and you can write your own custom matchers as BJ Clark has said and it would give you even more flexibility. I have used both custom and simple matchers and really sometimes a simple matcher is good enough. There are different ways you just got to pick one that suits your needs.

andHapp