Find or create record through factory_girl association

Slobodan Kovacevic picture Slobodan Kovacevic · Aug 22, 2011 · Viewed 24.3k times · Source

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.

Answer

Fernando Almeida picture Fernando Almeida · Aug 3, 2012

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.