我是FactoryGirl的新手。我来自赛程世界。
我有以下两种型号:
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
但我真的很想知道为什么有协会的工厂不工作。有了固定装置,我白白拥有了这一切。
我认为您正在尝试按"类工厂"对工厂进行分组,这不是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