在RSpec的默认失败消息中附加更多信息?

时间:2013-01-17 13:14:16

标签: rspec

我在这样的验证中测试了很多坏字符串:

['0', '3:a', 'xx:11', '-1', '-3:00', 'h', 'h2', 'h2h', 'm', 'm10', 'm10m', '2hm', 'h2m', 'hm2', '2m10h', '2m10m', '2h10h'].each do |input|
  FactoryGirl.build(:time_record, duration_string: input).should have(1).error_on('duration_string'), "Tested value was '#{input}'"
end

可悲的是,当其中一个失败时,消息expected 1 error on :duration_string, got 0并没有告诉我,哪一个失败了。我知道我可以传递显示的第二个参数而不是默认消息,如下所示:

x.should have(1).error_on('duration_string'), "Tested value was '#{input}'"

但这隐藏了原始信息。有没有办法只将我自己的消息附加到原始消息而不是替换它?

谢谢。

2 个答案:

答案 0 :(得分:5)

您可以使用其他消息捕获并重新引发异常:

['0', '3:a', 'xx:11', '-1', '-3:00', 'h', 'h2', 'h2h', 'm', 'm10', 'm10m', '2hm', 'h2m', 'hm2', '2m10h', '2m10m', '2h10h'].each do |input|
  begin
    FactoryGirl.build(:time_record, duration_string: input).should  have(1).error_on('duration_string'), "Tested value was '#{input}'"
  rescue RSpec::Expectations::ExpectationNotMetError => e
    e.message << "failed at #{input}"
    raise e
  end
end

答案 1 :(得分:1)

我这样解决了:

['0', '3:a', 'xx:11', '-1', '-3:00', 'h', 'h2', 'h2h', 'm', 'm10', 'm10m', '2hm', 'h2m', 'hm2', '2m10h', '2m10m', '2h10h'].each do |input|
  it "does not accept #{input}" do
    FactoryGirl.build(:time_record, duration_string: input).should have(1).error_on('duration_string'), "Tested value was '#{input}'"
  end
end

通过这种方式,您可以更便宜地获得更高的统计数据。 ;)