Ale*_*xey 40 ruby tdd rspec xunit
在rspec中:我可以像在xUnit样式测试框架中那样将消息附加到支票上吗?怎么样?
assert_equal value1, value2, "something is wrong"
Run Code Online (Sandbox Code Playgroud)
Chr*_*sen 56
should并should_not采用第二个参数(message)来覆盖匹配器的默认消息.
1.should be(2), 'one is not two!'
Run Code Online (Sandbox Code Playgroud)
默认消息通常非常有用.
更新:
对于RSpec 3:
expect(1).to eq(2), "one is not two!"
Run Code Online (Sandbox Code Playgroud)
Jör*_*tag 28
在RSpec中,打印合理的失败消息是匹配器的工作.RSpec附带的通用匹配器显然只能打印通用的非描述性失败消息,因为它们不了解您的特定域.这就是为什么建议您编写自己的特定于域的匹配器,这将为您提供更易读的测试和更可读的失败消息.
以下是RSpec文档中的示例:
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
Run Code Online (Sandbox Code Playgroud)
注意:仅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'
Run Code Online (Sandbox Code Playgroud)
有了这个:
user.should have_administrative_rights
Run Code Online (Sandbox Code Playgroud)
这将(大致)实现如下:
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
Run Code Online (Sandbox Code Playgroud)
就我而言,这是一个括号问题:
expect(coder.is_partial?(v)).to eq p, "expected #{v} for #{p}"
Run Code Online (Sandbox Code Playgroud)
这导致了错误的参数数量,而正确的方法是:
expect(coder.is_partial?(v)).to eq(p), "expected #{v} for #{p}"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10844 次 |
| 最近记录: |