2014-04-25 54 views
0

我正在嘗試爲驗證方法編寫RSpec測試。記錄更新,保存或創建時會觸發此方法。以下是我迄今爲止:使用RSpec和FactoryGirl測試關聯驗證

product.rb(模型)

class Product < ActiveRecord::Base 

validate :single_product 

    # Detects if a product has more than one SKU when attempting to set the single product field as true 
    # The sku association needs to map an attribute block in order to count the number of records successfully 
    # The standard self.skus.count is performed using the record ID, which none of the SKUs currently have 
    # 
    # @return [boolean] 
    def single_product 
    if self.single && self.skus.map { |s| s.active }.count > 1 
     errors.add(:single, " product cannot be set if the product has more than one SKU.") 
     return false 
    end 
    end 
end 

products.rb(FactoryGirl測試數據)

FactoryGirl.define do 
    factory :product do 
     sequence(:name) { |n| "#{Faker::Lorem.word}#{Faker::Lorem.characters(8)}#{n}" } 
     meta_description { Faker::Lorem.characters(10) } 
     short_description { Faker::Lorem.characters(15) } 
     description { Faker::Lorem.characters(20) } 
     sku { Faker::Lorem.characters(5) } 
     sequence(:part_number) { |n| "GA#{n}" } 
     featured false 
     active false 
     sequence(:weighting) { |n| n } 
     single false 

     association :category 

     factory :product_skus do 
      after(:build) do |product, evaluator| 
       build_list(:sku, 3, product: product) 
      end 
     end 
    end 
end 

product_spec.rb(單位測試)

require 'spec_helper' 

describe Product do 
    describe "Setting a product as a single product" do 
     let!(:product) { build(:product_skus, single: true) } 

     context "when the product has more than one SKU" do 

      it "should raise an error" do 
       expect(product).to have(1).errors_on(:single) 
      end 
     end 
    end 
end 

singe_product方法中可以看出,當單個屬性設置爲true並且產品具有多個關聯的SKU時,我試圖在單個屬性上觸發錯誤。但是,在運行測試時,產品沒有關聯的SKU,因此上述單元測試失敗。

如何在FactoryGirl中創建一個記錄並生成相關的SKU(可以計算在內)(例如:product.skus.count)並進行驗證?

回答

0

你可以寫這就像

it 'should raise an error' do 
    product = build(:product_skus, single: true) 

    expect(product).not_to be_valid 
    end 
+0

到downvoter:您可以not_to或to_not使用。一個是另一個的別名!所以,不,這不是一個不正確的語法! – Danny

相關問題