我是FactoryGirl的新手,我正在嘗試以下簡單場景?工廠女孩與現有對象創建關聯
factory :female, :class => Gender do
code 'Female'
end
factory :male, :class => Gender do
code 'Male'
end
factory :papas, :class => Customer do
first_name 'Jim'
last_name 'Papas'
association :gender, :factory => :male, :strategy => :build
end
factory :dumas, :class => Customer do
first_name 'Mary'
last_name 'Dumas'
association :gender, :factory => :female, :strategy => :build
end
然後在我的測試:
create(:male)
create(:female)
create(:papas)
create(:dumas)
注意,Customer類具有ASSOCATION belongs_to
Gender
類和說gender_id
應該存在一個驗證規則。我還對Gender
類進行了驗證,以驗證代碼的唯一性。
在create(:papas)
上述說法,在我的測試中,我得到的錯誤是將要創建的Customer
是無效的,因爲gender_id
是nil
。
如果我刪除與性別:strategy => :build
上Customer
:papas
工廠協會的話,我會得到一個錯誤,即試圖創建:papas
時,爲性別代碼已經存在。
我需要做什麼以便我的測試按照上面的要求創建數據?
請注意,在其他測試中,我還希望在沒有客戶的情況下創建性別。不要告訴我用工廠創建命令創建客戶,並讓客戶同時創建性別。如果我嘗試創建兩個同一性別的客戶,這也不起作用。
此外,必須有一個比一個更好的答案:
@male = create(:male)
@female = create(:female)
create(:papas, :gender => @male)
create(:dumas, :gender => @female)
(?當使用固定裝置,這些事情都準備出的現成要我返回到夾具)
雖然相當冗長VS燈具,你的答案是正確的。過去兩個月我一直在使用工廠女孩,而我的下一個項目仍將使用燈具! –
您可能會發現工廠的優勢在於您是否需要創建許多不同的客戶。您可以有一個male_customer和female_customer工廠,並將這些工廠用作不同客戶的父級工廠 - 這大大減少了冗長。很高興它的工作雖然! – Shadwell