我是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
但我真的想知道爲什麼工廠與協會不起作用。隨着燈具,我沒有這一切。
你可以發佈'NoMethodError'堆棧跟蹤?我想這將有助於瞭解在「Symbol」上嘗試調用'name'的方法。如果需要,將'--trace'添加到您運行測試的任何命令中以獲取完整跟蹤。 –