2013-01-17 61 views
4

我在验证测试有很多不好的字符串是这样的:将更多信息附加到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}'" 

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

谢谢。

回答

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 

这样,你也可以得到便宜了更高规格计数的统计数据。 ;)

4

可以捕获并与另一条消息再次加注例外:

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

谢谢!我同时以另一种方式解决问题,请参阅我的新答案。 –