I have a User model that belongs to a Group. Group must have unique name attribute. User factory and group factory are defined as:
Factory.define :user do |f| f.association :group, :factory => :group # ... end Factory.define :group do |f| f.name "default" end
When the first user is created a new group is created too. When I try to create a second user it fails because it wants to create same group again.
Is there a way to tell factory_girl association method to look first for an existing record?
Note: I did try to define a method to handle this, but then I cannot use f.association. I would like to be able to use it in Cucumber scenarios like this:
Given the following user exists: | Email | Group | | [email protected] | Name: mygroup |
and this can only work if association is used in Factory definition.
You can to use initialize_with
with find_or_create
method
FactoryGirl.define do factory :group do name "name" initialize_with { Group.find_or_create_by_name(name)} end factory :user do association :group end end
It can also be used with id
FactoryGirl.define do factory :group do id 1 attr_1 "default" attr_2 "default" ... attr_n "default" initialize_with { Group.find_or_create_by_id(id)} end factory :user do association :group end end
For Rails 4
The correct way in Rails 4 is Group.find_or_create_by(name: name)
, so you'd use
initialize_with { Group.find_or_create_by(name: name) }
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With