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 |
| test@email.com | Name: mygroup |
and this can only work if association is used in Factory definition.
I ended up using a mix of methods found around the net, one of them being inherited factories as suggested by duckyfuzz in another answer.
I did following:
I'm using exactly the Cucumber scenario you described in your question:
You can extend it like:
This will create 3 users with the group "mygroup". As it used like this uses 'find_or_create_by' functionality, the first call creates the group, the next two calls finds the already created group.
You can also use a FactoryGirl strategy to achieve this
You can use this gist. And then do the following
This is working for me, though.
You can to use
initialize_with
withfind_or_create
methodIt can also be used with id
For Rails 4
The correct way in Rails 4 is
Group.find_or_create_by(name: name)
, so you'd useinstead.
Usually I just make multiple factory definitions. One for a user with a group and one for a groupless user:
THen you can use these in your step definitions to create users and groups seperatly and join them together at will. For example you could create one grouped user and one lone user and join the lone user to the grouped users team.
Anyway, you should take a look at the pickle gem which will allow you to write steps like: