[英]How to DRY (these) RSpec tests using custom matcher
I currently have the following tests, which look like good candidates for a little DRY treatment: 我目前有以下测试,看起来像是进行一些DRY处理的良好候选人:
describe League do
context 'attributes validation' do
before(:each) do
@league = League.new
end
it 'should be invalid without a short_name' do
@league.attributes = valid_league_attributes.except(:short_name)
@league.should_not be_valid
@league.should have(1).error_on(:short_name)
@league.errors[:short_name].should == ["can't be blank"]
@league.short_name = 'NFL'
@league.should be_valid
end
it 'should be invalid without a long_name' do
@league.attributes = valid_league_attributes.except(:long_name)
@league.should_not be_valid
@league.should have(2).error_on(:long_name)
@league.errors[:long_name].should == ["can't be blank", 'is not included in the list']
@league.long_name = 'National Football League'
@league.should be_valid
end
end
end
Is it possible to make this more DRY using Custom Matchers or some other utility? 是否可以使用“自定义匹配器”或其他实用程序使它更干燥?
It is possible, but I wouldn't recommend it. 有可能,但我不建议这样做。 These two tests are sufficiently different that writing a method to wrap them into introduces more complexity than seems justified, and will make troubleshooting harder if one of the two tests should ever fail.
这两个测试的差异足够大,以至于编写一种将它们包装到一起的方法所带来的复杂性超出了合理的理由,并且如果两个测试之一失败了,将使故障排除更加困难。
You might want to have a look at shoulda 您可能想看看shoda
This would allow you to write 这可以让你写
describe League do
subject {League.new}
it {should validate_presence_of(:long_name)}
it {should validate_presence_of(:short_name)}
end
There's a bunch of other matchers for validations and associations too. 还有很多其他匹配器用于验证和关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.