factory girl nested factory

99封情书 提交于 2019-11-28 20:45:31

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

Then in your tests:

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")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!