2013-12-20 58 views
1

我有一個很基本的rails應用程序,我正在研究。FactoryGirl協會

零件處於某些狀態(state_id),它們由用戶(user_id)創建並與它們有關聯的類型(type_id)。

試圖爲部分創建一個工廠,我有:

FactoryGirl.define do 
    factory :part do 
    name "blah" 
    association :state_id, factory: :state 
    association :user_id, factory: :user 
    association :techtype_id, factory: :techtype 
    end 

    factory :state do 
    name "blah" 
    end 

    factory :user do 
    login "blah" 
    end 

    factory :techtype do 
    name "blah" 
    example "bleh" 
    end 
end 

然而FactoryGirl.create(:部分)似乎不工作:

2.0.0p353 :001 > part = FactoryGirl.create(:part) 
[SQL insert for State, User, and Techtype outputs here and succeeds, then...] 
ActiveRecord::RecordInvalid: Validation failed: 
    State can't be blank, Techtype can't be blank, User can't be blank 

我試圖消除_id屬性(即association :state, factory: :state),但不工作,我只是得到一個NoMethodError: undefined method 'state=' for #<Part:0x007fa3e8e798a0>。我也試過使用短格式關聯(即state而不是association :state_id, factory: :state),但我獲得了相同的NoMethodError

回答

3

你的模型應該像這樣

class Part < ActiveRecord::Base 
    belongs_to :state 
    belongs_to :user 
    belongs_to :techtype 
end 

的,工廠這樣

factory :part do 
    name "blah" 
    association :state 
    association :user 
    association :techtype 
    end 
+0

原來,在我的代碼凝視之後,我離開了我的部分類belongs_to的屬性。第一次與ActiveRecord進行關聯,所以我錯過了。由於 – mrbucket

+0

對於新factory_girl語法: '工廠:一部分做 名「嗒嗒」 狀態 用戶 techtype end' 假設你有一個國家的名稱,用戶和techtype工廠。 FactoryGirl會知道如何去做其餘的事情。 – astephenb