Slobodan Kovacevic Slobodan Kovacevic - 10 months ago 88
Ruby Question

Find or create record through factory_girl association

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
# ...

Factory.define :group do |f| "default"

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 |
| | Name: mygroup |

and this can only work if association is used in Factory definition.

Answer Source

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:

# in groups.rb factory

def get_group_named(name)
  # get existing group or create new one
  Group.where(:name => name).first || Factory(:group, :name => name)

Factory.define :group do |f| "default"

# in users.rb factory

Factory.define :user_in_whatever do |f| { |user| get_group_named("whatever") }