0

我是 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

但是我真的很想知道为什么与协会的工厂不起作用。有了 Fixtures,我什么都没有了。

4

1 回答 1

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
于 2012-05-02T07:57:59.840 回答