1

I'm trying to have a factory build an Offering object with a child object Rating that will receive the item_id from it's parent.

FactoryGirl.define do
  factory :offering do
    item_id nil
    element_id nil
    association :rating, factory: :rating, strategy: :build, :item => item_id
  end
end

The Offering is created with

offering = FactoryGirl.create :offering, item_id: 21, element_id: 211

But when run, it aborts with an error

Failure/Error: offering = FactoryGirl.create :offering, item_id: 21, element_id: 211
 ArgumentError:
   Trait not registered: item_id

I assume the error occurs because the item_id in the association definition is not "lazy" and therefor undefined.

How can I solve this?

4

2 回答 2

1

不幸的是,我不知道有什么方法可以对关联进行惰性评估(如果我在这方面错了,请有人纠正我)。您最好的选择可能是使用回调。假设您定义了一个工厂:rating,请尝试替换您的

association :rating, factory: :rating, strategy: :build, :item => item_id

after(:create) do |offering, evaluator|
  FactoryGirl.build(:rating, item_id: evaluator.item_id, element_id: evaluator.element_id)  
end
于 2013-08-12T21:37:11.510 回答
1

您可以懒惰地定义关联:

FactoryGirl.define do
  factory :offering do
    item_id nil
    element_id nil
    rating { association(:rating, :item => item_id) }
  end
end
于 2015-11-25T22:42:04.377 回答