如何在Factory Girl中正确设置关联?

时间:2012-05-01 21:27:54

标签: ruby-on-rails-3 factory-bot

我是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我一无所获。

1 个答案:

答案 0 :(得分: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