2012-01-14 32 views
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 

是否可以使用自定義匹配器,使這個更幹或其他一些實用程序?

回答

0

這是可能的,但我不會推薦它。這兩個測試有很大的不同,因爲編寫一個方法來包裝它們會帶來比看起來合理的更多的複雜性,並且如果兩個測試中的一個測試失敗,將會使故障排除變得更加困難。

0

你可能想看看shoulda

這將使你寫

describe League do 
    subject {League.new} 

    it {should validate_presence_of(:long_name)} 
    it {should validate_presence_of(:short_name)} 
end 

還有很多其他的匹配器進行驗證和關聯太。

+0

我相信validate_presence_of只是檢查以確保定義了該類方法。它並不實際運行並檢查屬性的值。 – keruilin 2012-01-14 17:03:30

+0

不,它確實運行驗證並檢查對象的錯誤是否包含預期的錯誤 - 請參閱https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_model/allow_value_matcher.rb – 2012-01-14 17:27:27