Black Dynamite
Black Dynamite

Reputation: 4147

Ruby Factory Girl Creating Multiple Objects

I am a newcomer to using Factory Girl and I feel I may have some misunderstandings about how it is suppose to work and how I am supposed to use it. Here is a snippet of the problem code.

FactoryGirl.define do                      
   factory :li_store , :class => Store do   
   ...store stuff...blah...blah         
end                                      

factory :li_line_item_stores_two,:class=>LineItemsStore do   
   association :store, :factory=>:li_store                    
   association :line_item , :factory=>:li_line_item_two                                                         
end                                                             
factory :li_line_item_stores_three,:class=>LineItemsStore do 
   association :store :factory => :li_store                                   
   association :line_item , :factory => :li_line_item_three                                                 
end

Now if I access :li_line_item_stores_two and :li_line_item_stores_two each one has a different object for its store property. For my test I need both objects to have the same store object.

Does anyone know what facet of FactoryGirl I am missing or how I should go about making sure both objects both reference the same store object ?

Any help is greatly appreciated.

Upvotes: 1

Views: 2651

Answers (1)

Tom L
Tom L

Reputation: 3409

You want to define baseline objects and attributes in your factories.rb file. You don't want to define a bunch of different identical versions of an object. Instead, factories.rb should look something like:

FactoryGirl.define do
  factory :li_store do 
    whatever
  end

  factory :li_line_item do
    whatever
  end

  factory :li_line_item_store do
    association :store, :factory => :li_store
    association :line_item, :factory => :li_line_item
  end
end

Those attributes are then overridable (or can be left with baseline values) in your tests:

def test_something
  store = Factory(:li_store)
  li_line_item_store_one = Factory(:li_line_item_store, :store => store)
  li_line_item_store_two = Factory(:li_line_item_store, :store => store)
end

With the above, you now have two li_line_item_store instances with different line items and the same store.

Upvotes: 3

Related Questions