工厂女孩筑巢工厂 [英] factory girl nested factory

查看:55
本文介绍了工厂女孩筑巢工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个属于角色模型的帐户模型.

I have an account model that belongs_to a role model.

factory :role do
  name "student"
end

factory :account do
  user
  role
end

第一个工厂创建一个名为学生"的角色.第二家工厂创建一个帐户,该帐户与在前一个工厂中创建的学生角色相关联.它还与用户相关联...对于这个问题并不重要.

The first factory creates a role named "student". The second factory creates an account that is associated to the student role that was created in the previous factory. It also is associated with a user...which is not important for this question.

我有许多角色要测试(管理员,学生,助理)...我不想在角色工厂中指定学生" ...那太静态了.如何指定在创建帐户工厂时要创建的角色?喜欢:

I have many roles to be tested (admin, student, assistant)... I dont want to specify 'student' in the role factory...thats too static. How do I specify what role to create at the time the account factory is created? Like:

  factory :account do
    user
    role_id { factory :role { name: "admin"} }
  end

完成此任务的最佳方法是什么?

What is the best way to accomplish this?

推荐答案

如果您想要纯FG解决方案,则可以使用Traits:

If you want a purely FG solution, you could use Traits:

factory :account do
  user

  trait :student do
    association :role, :name => "student"
  end

  trait :admin do
    association :role, :name => "admin"
  end
end

FactoryGirl.create :account, :student
FactoryGirl.create :account, :admin

但是,创建工厂对象时可以覆盖工厂的属性.这样可以提供更大的灵活性:

However, you can override the properties of the factory when you create the factory object. This allows for more flexibility:

FactoryGirl.create(:account,
  :role => FactoryGirl.create(:role, :name => "student")
)

由于这显然很冗长,因此我将创建一个辅助方法:

Since this is obviously verbose, I'd create a little helper method:

def account_as(role, options = {})
  FactoryGirl.create(:account,
    options.merge(:role => FactoryGirl.create(:role, :name => "student"))
  )
end

然后在您的测试中:

let(:account) { account_as "student" }

或者,您可以缩短角色生成器,以便可以像这样使用它:

Alternately, you could just shorten up your role generator so you could use it like:

def role(role, options = {})
  FactoryGirl.create :role, options.merge(:name => role)
end

account = FactoryGirl.create :account, :role => role("student")

这篇关于工厂女孩筑巢工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆