How to attach a message to RSpec check?
For RSpec 3+:
The message could be customized as a string or using a proc(check the reference).
expect(1).to eq(2), 'one is not two!'
Customized message RSpec tries to provide useful failure messages, but for cases in which you want more specific information, you can define your own message right in the example. This works for any matcher other than the operator matchers.
source @ relishapp
For older RSpec versions
should
and should_not
take a second argument (message
) that overrides the matcher’s default message.
1.should be(2), 'one is not two!'
The default messages are usually pretty useful though.
In RSpec, it's the matcher's job to print a sensible failure message. The generic matchers that ship with RSpec can obviously only print generic non-descript failure messages, since they don't know anything about your particular domain. That's why it is recommended that you write your own domain-specific matchers, which will give you both more readable tests and more readable failure messages.
Here's an example from the RSpec documentation:
require 'rspec/expectations'
RSpec::Matchers.define :be_a_multiple_of do |expected|
match do |actual|
(actual % expected).zero?
end
failure_message_for_should do |actual|
"expected that #{actual} would be a multiple of #{expected}"
end
failure_message_for_should_not do |actual|
"expected that #{actual} would not be a multiple of #{expected}"
end
description do
"be multiple of #{expected}"
end
end
Note: only match
is required, the others will be generated automatically. However, the whole point of your question is of course that you do not like the default messages, so you need to at least also define failure_message_for_should
.
Also, you can define match_for_should
and match_for_should_not
instead of match
if you need different logic in the positive and negative case.
As @Chris Johnsen shows, you can also explicitly pass a message to the expectation. However, you run the risk of losing the readability advantages.
Compare this:
user.permissions.should be(42), 'user does not have administrative rights'
with this:
user.should have_administrative_rights
That would (roughly) be implemented like this:
require 'rspec/expectations'
RSpec::Matchers.define :have_administrative_rights do
match do |thing|
thing.permissions == 42
end
failure_message_for_should do |actual|
'user does not have administrative rights'
end
failure_message_for_should_not do |actual|
'user has administrative rights'
end
end
In my case it was a problem of parenthesis:
expect(coder.is_partial?(v)).to eq p, "expected #{v} for #{p}"
this resulted in a wrong number of arguments, while the correct way is:
expect(coder.is_partial?(v)).to eq(p), "expected #{v} for #{p}"