Reputation: 712
I know I can give factory girl static data values like this:
factory :post do
title 'New post'
number 7
end
But what if I have more than one value for each title and number. What if title is 'New Post', 'Old Post', 'Hello' and number is 7, 8, 9. How would I pass that data to factory girl? Should I use an array or use multiple do end blocks?
Upvotes: 0
Views: 940
Reputation: 760
For numbers you can use FactoryGirl sequences:
FactoryGirl.define do
sequence :email do |n|
"person#{n}@example.com"
end
end
To generate some random strings there is a gem Faker
:
FactoryGirl.define do
factory :post do
title { Faker::Lorem.sentence }
end
end
Faker can be used to generate random emails, strings, e-commerce items, addresses and lots of other things, see at https://github.com/stympy/faker
Upvotes: 1
Reputation: 984
If you want to pass values as arguments:
factory :post do
title 'Default Title'
end
# create(:post, title: 'Custom Title')
If you want just randomize values then simply:
factory :post do
title { ['New Post', 'Old Post', 'Hello'].sample }
end
Upvotes: 3
Reputation: 54882
You can simply do:
posts_attrs = [{ title: 'new', number: 6}, { title: 'old' }]
posts_attrs.each do |post_attrs|
factory :post do
title post_attrs[:title] || 'default title'
number post_attrs[:number] || 1
end
end
Upvotes: 1