Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing factory_girl factories in *other* factories

Tags:

I'm using the factory_girl plugin in my rails application. For each model, I have a corresponding ruby file containing the factory data e.g.

Factory.define :valid_thing, :class => Thing do |t|
  t.name 'Some valid thing'
  # t.user ???
end

I have lots of different types of users (already defined in the user factory). If I try the following though:

Factory.define :valid_thing, :class => Thing do |t|
  t.name 'Some valid thing'
  t.user Factory(:valid_user) # Fails
end

I get the following error:

# No such factory: valid_user (ArgumentError)

The :valid_user is actually valid though - I can use it in my tests - just not in my factories. Is there any way I can use a factory defined in another file in here?

like image 393
Michelle Avatar asked Feb 10 '10 00:02

Michelle


2 Answers

You should use this code:

Factory.define :valid_thing, :class => Thing do |t|
  t.name 'Some valid thing'
  t.user { Factory(:valid_user) }
end

Wrapping the call in {} causes Factory Girl to not evaluate the code inside of the braces until the :valid_thing factory is created. This will force it to wait until the :valid_user factory has been loaded (Your example is failing because it is not yet loaded), it will also cause a new :valid_user to be created for each :valid_thing rather than having the same user for all :valid_thing's (Which is probably what you want).

like image 112
Gdeglin Avatar answered Sep 18 '22 17:09

Gdeglin


Try using the association method like:

Factory.define :valid_thing, :class => Thing do |t|
  t.name 'Some valid thing'
  t.association :valid_user
end
like image 21
Peter Brown Avatar answered Sep 19 '22 17:09

Peter Brown