Factory Girl Newbie: Calling (not creating) an existing factory as an association
-
26-09-2019 - |
Question
I have some factorygirl factories that involve associations to other factories. For example:
FactoryGirl.define do
factory :user do |f|
f.sequence(:email) { |n| "user#{n}@example.com" }
f.password "foobar"
f.password_confirmation { |u| u.password }
f.role_id 2
f.association :role, :factory => :role
end
end
The problem is that if I call Factory(:user) twice, I get a duplication error (there's a uniqueness constraint on the role.name column)
So the question is: how do I specify that the above should create the :role factory if it doesn't already exist, but use the existing one if it doesn't?
Solution
Why dont you use a sequence on Factory role name. For example define sequence for role name like in
FactoryGirl.sequence :role_name do |n|
"role#{n}"
end
and define Factory role like in
factory.role do |role|
f.name Factory.next :role_name
end
By doing this, each time a new role will be created but with a different role_name. You could pass the role to Factory.build by creating the role in each test. But I find that cumbersome.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow