FactoryGirl-创建变量

时间:2017-05-16 01:31:07

标签: ruby-on-rails factory-bot

我有一个项目,大量的工厂是这样的:

FactoryGirl.define do
  factory :terms_document do
    created_by { FactoryGirl.create(:user) }
    updated_by { FactoryGirl.create(:user) }
    ...
  end
end

如何在开始时创建一个用户,我可以在整个工厂使用?

1 个答案:

答案 0 :(得分:2)

您可以将缓存方法添加到工厂文件中:

def user
  @user ||= FactoryGirl.create(:user)
end

FactoryGirl.define do
  factory :terms_document do
    created_by user
    updated_by user
    ...
  end
end

更新:如果您需要针对不同工厂实例的不同用户:

def user(term_document)
  @users ||= {}
  @users[term_document] ||= FactoryGirl.create(:user)
end

FactoryGirl.define do
  factory :terms_document do
    ...
    after(:build) do |term_document|
      created_by user(term_document)
      updated_by user(term_document)
    end
  end
end