aarkerio
aarkerio

Reputation: 2364

FactoryGirl: create_list from a previous create_list

I'm pretty new using FG and I'm trying to create several objects from a previous "create_list" call. Is this the correct way to do it?

 let(:questions) { FactoryGirl.create_list :question, 5 }
 let(:answers)   { questions.map do |q|
                     FactoryGirl.create :answer, question: q
                   end
                 }

Looks smelly to me.

Upvotes: 0

Views: 564

Answers (2)

Carlos Ramirez III
Carlos Ramirez III

Reputation: 7434

All of the FactoryGirl builder methods support providing a block which is yielded the newly created object. Using this, you can create your records and associations in a single call.

For example,

FactoryGirl.create_list(:question, 5) do |question|
   question.answers = FactoryGirl.build_list(:answer)
   # or...
   # question.answers.create(FactoryGirl.attributes_for(:answer))
end

Resources

Upvotes: 1

Marc Lapierre
Marc Lapierre

Reputation: 11

This depends on your data model.

Do questions require an answer?

If yes, consider FactoryGirl associations

If not, create them in your tests if and when you need them as you will likely need to test cases where questions do not have answers.

Upvotes: 1

Related Questions