【发布时间】:2010-11-15 11:02:06
【问题描述】:
在 RSpec 中:我可以像在 xUnit 风格的测试框架中那样将消息附加到检查吗?怎么样?
assert_equal value1, value2, 'something is wrong'
【问题讨论】:
在 RSpec 中:我可以像在 xUnit 风格的测试框架中那样将消息附加到检查吗?怎么样?
assert_equal value1, value2, 'something is wrong'
【问题讨论】:
对于 RSpec 3+:
消息可以自定义为字符串或使用过程(检查参考)。
expect(1).to eq(2), 'one is not two!'
自定义消息 RSpec 尝试提供有用的失败消息,但对于您想要更多的情况 具体信息,您可以在示例中定义自己的消息权。这适用于 除运算符匹配器之外的任何匹配器。
对于旧的 RSpec 版本
should 和 should_not 采用第二个参数 (message),它会覆盖匹配器的默认消息。
1.should be(2), 'one is not two!'
不过,默认消息通常非常有用。
【讨论】:
#should ==?
1.should(nil, 'one is not two!') == 2 (ick),但这确实有效,因为== 运算符匹配器看起来总是生成自己的消息。
eq 代替== 即1.should eq(nil), 'one is not two!'
在 RSpec 中,匹配器的工作是打印合理的失败消息。 RSpec 附带的通用匹配器显然只能打印通用的非描述性失败消息,因为它们对您的特定域一无所知。这就是为什么建议您编写自己的特定于域的匹配器,这将为您提供更易读的测试和更易读的失败消息。
这是来自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
注意:只需要match,其他的会自动生成。但是,您问题的全部意义当然是您不喜欢默认消息,因此您至少还需要定义failure_message_for_should。
另外,如果您在正负情况下需要不同的逻辑,您可以定义match_for_should 和match_for_should_not 而不是match。
正如@Chris Johnsen 所示,您还可以明确地将消息传递给期望。但是,您可能会失去可读性优势。
比较一下:
user.permissions.should be(42), 'user does not have administrative rights'
用这个:
user.should have_administrative_rights
这将(大致)这样实现:
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
【讨论】:
就我而言,这是括号的问题:
expect(coder.is_partial?(v)).to eq p, "expected #{v} for #{p}"
这导致参数数量错误,而正确的方法是:
expect(coder.is_partial?(v)).to eq(p), "expected #{v} for #{p}"
【讨论】:
.to be(true) .