FactoryGirl协会参考

时间:2013-08-26 07:09:32

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

我有四个模型:UserProductOwnershipLocationUserProduct有一个LocationLocation属于UserProduct(多态模型)。

我想使用FactoryGirl创建与其所有者具有相同位置的产品。

factory :location do
  sequence(:address) { |n| "#{n}, street, city" }
end

factory :user do
  sequence(:name)  { |n| "Robot #{n}" }
  sequence(:email) { |n| "numero#{n}@robots.com"}
  association :location, factory: :location
end

factory :product do
  sequence(:name) { |n| "Objet #{n}" }
  association :location, factory: :location
end

factory :ownership do
  association :user, factory: :user
  association :product, factory: :product
end

我在产品型号文件中创建了一个方法,只需执行product.owner即可检索产品的所有者。

我想调整产品工厂,以便用product.owner.location替换有效位置。我怎么能这样做?

编辑1

我想这样使用它:

首先我创建一个用户

FactoryGirl.create(:user)

后来我创建了一个产品

FactoryGirl.create(:product)

当我联系他们时

FactoryGirl.create(:current_ownership, product: product, user: user)

我希望我的产品的位置成为他的主人之一。

2 个答案:

答案 0 :(得分:10)

使用以下代码。

factory :user do
  sequence(:name)  { |n| "Robot #{n}" }
  sequence(:email) { |n| "numero#{n}@robots.com"}
  association :location, factory: :location

  factory :user_with_product do
    after(:create) do |user|
      create(:product, location: user.location)
    end
  end
end

要创建记录,只需使用user_with_product工厂。

更新:

在回答您的问题更新时,您可以向after(:create)工厂

添加ownership回调
factory :ownership do
  association :user, factory: :user
  association :product, factory: :product

  after(:create) do |ownership|
    # update ownership.user.location here with ownership.user.product
  end
end

这个问题是您当前的关联设置。由于location属于用户或产品,因此外键位于其中。因此,location不能同时属于用户和产品。

答案 1 :(得分:1)

使用after_create callback应该可以做到这一点

factory :ownership do
  user # BONUS - as association and factory have the same name, save typing =)
  product
  after(:create) { |ownership| ownership.product.location = ownership.user.location }
end
相关问题