Rebekah Waterbury
Rebekah Waterbury

Reputation: 23796

Can one uniquely initialize each object created by the create_list method in FactoryGirl?

In order to do this, I imagine passing an array of hashes to the create_list method. I am considering something that would look like this:

FactoryGirl.create_list(
  :person, 3, [
    {name: 'Rebekah', description: 'A woman with straight brown hair'}, 
    {name: 'Day', description: 'A man with curly brown hair'}, 
    {name: 'Ihsan', description: 'A boy with wavy blond hair'}
  ]
)

This would persist three objects initialized with the custom name and description values.

Is there any way to do this directly or ought I just loop through the array creating an individual instance with each set of unique values?

Upvotes: 1

Views: 588

Answers (1)

paulorcdiniz
paulorcdiniz

Reputation: 164

Do you really need them to be different? If you do, I see two options:

1- Set up the factory properties in a sequence. Like this:

FactoryGirl.define do
  factory :person do
    sequence(:name) { |n| "Person number #{n}" }
  end

2- Create a list and set them up individually

list = FactoryGirl.create_list(:person, 3)
    list.each do |person|
    #setting up
end

There are other answers, but I would go with the first

Upvotes: 2

Related Questions