Slobodan Kovacevic Slobodan Kovacevic - 22 days ago 6
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
# ...
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.

Answer

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)
end

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

# in users.rb factory

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