将更多信息附加到RSpec';默认的失败消息?

将更多信息附加到RSpec';默认的失败消息?,rspec,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_

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

['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
x.should have(1).error_on('duration_string'), "Tested value was '#{input}'"
不幸的是,当其中一个失败时,消息
expected 1 error on:duration\u string,get 0
没有告诉我哪一个失败了。我知道我可以传递显示的第二个参数,而不是默认消息,如下所示:

['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
x.should have(1).error_on('duration_string'), "Tested value was '#{input}'"
但这隐藏了最初的信息。有没有办法只将我自己的消息附加到原始消息中,而不是替换它


谢谢。

您可以通过另一条消息捕获并重新释放异常:

['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
['0','3:a','xx:11','-1','-3:00','h','h2','h2h','m','m10','m10m','2hm','h2m','hm2','2m10h','2m10m','2h10h']|
开始
FactoryGirl.build(:time_record,duration_string:input)。应该有(1)。错误发生在('duration_string'),“测试值为“#{input}”
rescue RSpec::Expections::ExpectationNotMetError=>e
e、 消息我这样解决它:

['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

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

谢谢大家!!我同时用另一种方法解决了这个问题,看看我的新答案。