maahd
maahd

Reputation: 712

Factory girl multiple values

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

Answers (3)

IvanSelivanov
IvanSelivanov

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

nsave
nsave

Reputation: 984

  1. If you want to pass values as arguments:

    factory :post do
      title 'Default Title'
    end
    
    # create(:post, title: 'Custom Title')
    
  2. If you want just randomize values then simply:

    factory :post do
      title {  ['New Post', 'Old Post', 'Hello'].sample }
    end
    

Upvotes: 3

MrYoshiji
MrYoshiji

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

Related Questions