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")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…