如果你想要一个纯粹的 FG 解决方案,你可以使用 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
但是,您可以在创建工厂对象时覆盖工厂的属性。这允许更大的灵活性:
FactoryGirl.create(:account,
:role => FactoryGirl.create(:role, :name => "student")
)
由于这显然很冗长,我将创建一个小辅助方法:
def account_as(role, options = {})
FactoryGirl.create(:account,
options.merge(:role => FactoryGirl.create(:role, :name => "student"))
)
end
然后在你的测试中:
let(:account) { account_as "student" }
或者,你可以缩短你的角色生成器,这样你就可以像这样使用它:
def role(role, options = {})
FactoryGirl.create :role, options.merge(:name => role)
end
account = FactoryGirl.create :account, :role => role("student")