Tony Han
Tony Han

Reputation: 2230

Why do I get the same object when I use create_list in the FactoryGirl and the sample method?

I use factory girl to define a object like this:

factory :event do
  #...
  category ['Life', 'Course', 'Speek'].sample
  #...
end

Then in the spec/models/event_spec.rb, I have this:

before(:each) do
  @events = FactoryGirl.create_list(:event, 10, node: school) 
end
  #...
binding.pry   

But when I used pry to check the @events, I found that all the event in the @events has the same category.

I want to know why and how to solve it ? Thanks in advance.

Upvotes: 1

Views: 922

Answers (1)

cdesrosiers
cdesrosiers

Reputation: 8892

The code category ['Life', 'Course', 'Speek'].sample only runs once (when the factory is defined). If you want to generate a new category each time an event is created or built, you can use a sequence as follows:

sequence(:category) { ['Life', 'Course', 'Speek'].sample }

Upvotes: 4

Related Questions