2012-05-01 54 views
0

我是FactoryGirl的新手。我來自燈具世界。如何在Factory Girl中正確設置關聯?

我有以下兩種模式:

class LevelOneSubject < ActiveRecord::Base 
    has_many :level_two_subjects, :inverse_of => :level_one_subject 
    validates :name, :presence => true 
end 

class LevelTwoSubject < ActiveRecord::Base 
    belongs_to :level_one_subject, :inverse_of => :level_two_subjects 
    validates :name, :presence => true 
end 

而且我想這樣做在工廠以下內容:

FactoryGirl.define do 
    factory :level_one_subject, class: LevelOneSubject do 
    factory :social_sciences do 
     name "Social Sciences" 
    end 
    end 

    factory :level_two_subject do 
    factory :anthropology, class: LevelTwoSubject do 
     name "Anthropology" 
     association :level_one_subject, factory: social_sciences 
    end 

    factory :archaelogy, class: LevelTwoSubject do 
     name "Archaelogy" 
     association :level_one_subject, factory: social_sciences 
    end 
    end 
end 

然後,當我使用工廠在這樣的規格:

it 'some factory test' do 
    anthropology = create(:anthropology) 
end 

我得到的錯誤:

NoMethodError: undefined method `name' for :anthropology:Symbol 

有人可以幫忙嗎?

如果我不設置在工廠的關聯,然後我沒有得到這個錯誤,但我得到的是level_one_subject_id必須存在,只有下面的測試代碼中的錯誤的工作原理:

it 'some factory test' do 
    social_sciences = create(:social_sciences) 
    anthropology = create(:anthropology, :level_one_subject_id => social_sciences.id) 
end 

但我真的想知道爲什麼工廠與協會不起作用。隨着燈具,我沒有這一切。

+0

你可以發佈'NoMethodError'堆棧跟蹤?我想這將有助於瞭解在「Symbol」上嘗試調用'name'的方法。如果需要,將'--trace'添加到您運行測試的任何命令中以獲取完整跟蹤。 –

回答

0

我認爲你正在試圖通過'班級工廠'來組建工廠,這不是FactoryGirl的工作方式。如果命名適當,它會從工廠名稱本身推導出ActiveRecord類。如果您的工廠名稱與類名稱不同,我們需要使用類名稱參數明確指定類名稱。這應該工作:

FactoryGirl.define do 
    factory :level_one_subject do # automatically deduces the class-name to be LevelOneSubject 
     name "Social Sciences" 
    end 

    factory :anthropology, class: LevelTwoSubject do 
     name "Anthropology" 
     level_one_subject # associates object created by factory level_one_subject 
    end 

    factory :archaelogy, class: LevelTwoSubject do 
     name "Archaelogy" 
     level_one_subject # associates object created by factory level_one_subject 
    end 
end 
+0

正確。如果我想把'''factory:level_one_subject''命名爲'''social_sciences''',我必須在它的名字旁邊放置'''class:LevelOneSubject''',然後在二級主題寫'''關聯:level_one_subject,:factory =>:social_sciences'''(而不是'''level_one_subject''') –

+0

是的,你說得對。 – Salil

相關問題