Dan Andreasson
Dan Andreasson

Reputation: 16212

How to create a list of factories with one value incremented

I am using factory_girl_rails together with RSpec.

I want x Placement created and inserted into a array with one of the attributes incrementing its value.

I have a version that is working, but I would like to make use of factory girl as much as possible.

My working solution

def create_placements(x)
  x.times.map { |i| create :placement, foo: i }
end

Can it be achieved with factory girl only? Something like create_list :placement, x, foo: 1..x ?

Upvotes: 0

Views: 2645

Answers (2)

MatayoshiMariano
MatayoshiMariano

Reputation: 2106

A little bit late, but you can do that with sequences.

In your case, in the file where you defined the factory placement, you should add as a child the factory placement_foo_increment or whatever the name you want.

Then the factory should be:

factory :placement_foo_increment do
  sequence(:foo) { |n| n - 1 }
end

The - 1 is there becase n starts from 1, and in your code it starts from zero.

Upvotes: 0

Piotr Kruczek
Piotr Kruczek

Reputation: 2390

FactoryGirl has the method *_list, e. g. create_list - more info here.

However it only accepts one set of data and uses it for all of its 'subjects', so if you wanted each of them to differ in some way, I think your loop is the best approach here.

Upvotes: 3

Related Questions