Factory_bot: create_list with different values for the same attribute

Created on 6 Jun 2015  路  6Comments  路  Source: thoughtbot/factory_bot

Is there any way to use create_list with different values for the same attribute?

for eg. I would like to do something like
FactoryGirl.create_list(:student, 2, gender: [male, female])
and it will give me 2 students with 1 male 1 female

Most helpful comment

@syedrakib FB + Ruby should work well in situations like this:

%w(NYC Boston SF Austin).map do |tb_location|
  FactoryBot.create(:location, city: tb_location)
end

All 6 comments

@sohymg
No there is no way to use create_list with different values for the same attribute

fast-forward 3 years..... is this still not possible with factory bot?

@syedrakib FB + Ruby should work well in situations like this:

%w(NYC Boston SF Austin).map do |tb_location|
  FactoryBot.create(:location, city: tb_location)
end

Since v5.2.0 you can do this:

twenty_somethings = create_list(:user, 10) do |user, i|
  user.date_of_birth = (20 + i).years.ago
end

@emmanuelgautier1994 that is good, but I just noticed it doesn't persist the setted attribute, unless I call .save manually. Siince it's create_list method, I expected it to be automacally saved with other attributes

@juniorjp Thanks for the comment. I see why you might expect that, but the block passed to any strategy will always yield the complete, already-built object. For the singular methods, it identical to using tap:

create(:user).tap do |user|
end

For the *_list methods it ends up being roughly equivalent to using each:

create_list(:user, 10).each do |user|
end

The feature added here offers something like each_with_index:

create_list(:user, 10).each_with_index do |user, i|
end

We could probably do a better job of documenting this behavior.

Was this page helpful?
0 / 5 - 0 ratings