FactoryGirl具有相同值的不同对象

时间:2018-07-25 10:11:38

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

我有一个Transaction模型,该模型具有2个buyer类型的属性sellerUser

我需要创建一个具有相同买卖双方的工厂。

我已经尝试过了:

FactoryGirl.define do
 factory :transaction do
   [...]
   factory :same_user_transaction do
      user = create(:user)
      buyer = user
      seller = user
   end
 end
end

但这不起作用。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

尝试:

FactoryGirl.define do
 factory :transaction do
   [...]
   factory :same_user_transaction do
      buyer  { create(:user) }
      seller { buyer }
   end
 end
end

如果您有用户工厂,则其他方法可以是:

factory :same_user_transaction do
  association :buyer, factory: :user
  seller { buyer }
end

或者更好,使用别名:

factory :user, aliases: [:buyer] do
  first_name    "John"
  last_name     "Doe"
  date_of_birth { 18.years.ago }
end

factory :same_user_transaction do
  buyer
  seller { buyer }
end

参考文献:https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#aliases