1
我現在有下面的測試,看起來像好的候選人有點乾燥處理:怎麼幹(這些)RSpec的測試使用自定義匹配
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
是否可以使用自定義匹配器,使這個更幹或其他一些實用程序?
我相信validate_presence_of只是檢查以確保定義了該類方法。它並不實際運行並檢查屬性的值。 – keruilin 2012-01-14 17:03:30
不,它確實運行驗證並檢查對象的錯誤是否包含預期的錯誤 - 請參閱https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_model/allow_value_matcher.rb – 2012-01-14 17:27:27