Question

Is there a way to have multiple versions of the same factory? For example, a user factory.

FactoryGirl.define do
  factory :user#1 do
    name 'John Doe'
    date_of_birth { 21.years.ago }
  end

  factory :user#2 do
    name 'Jane Doe'
    date_of_birth { 25.years.ago }
  end
end

is there something like this, so that I could call FactoryGirl.create :user#1 for John or FactoryGirl.create :user#2 for Jane?

The user factory is an example I don't actually use but my real factory is using a lot of data. I find it cumbersome to manually change a lot of data everytime I need another user.

Was it helpful?

Solution

You do not have to declare two times

just follow

FactoryGirl.define do
  factory :user do
    name
    date_of_bith
  end
end

Now Dynamically you can call

user1 = FactoryGirl.create(:user, name: 'John doe', date_of_birth: 21.year.ago)
user2 = FactoryGirl.create(:user, name: 'Jane doe', date_of_birth: 25.year.ago) 

OTHER TIPS

As opposed to providing all the data in the call, I just make my factories dynamic by using sequences to give me unique data.

FactoryGirl.define do
  factory :mail_user do
    mail_domain
    account
    sequence :userid do |n|
        "mailuser-#{n}"
    end
    passwd "This!sADecentPassword11212"
    active :true
    filter :false
  end
end

or by using traits / inheritance to give me the exact user data I need

FactoryGirl.define do
  factory :administrator do
    isp
    sequence :email do |n|
      "user#{n}@example.com"
    end
    active true
    name "Random Awesome Admin"
    password '123Abc#$1'
    password_confirmation '123Abc#$1'

    trait :inactive do
      active false
    end

    trait :system do
      roles [:system_admin]
    end

    trait :admin do
      roles [:admin ]
    end

    trait :realm do
      roles [:realm_admin]
    end

    trait :helpdesk do
      roles [ :helpdesk ]
    end

    trait :dns do
      roles [ :dns_admin ]
    end

    factory :inactive_administrator, traits: [:inactive]
    factory :helpdesk_admin, traits: [:helpdesk]
    factory :system_admin, traits: [:system]
    factory :admin, traits: [:admin]
    factory :realm_admin, traits: [:realm]
    factory :dns_admin, traits: [:dns]
  end
end

Since in most cases I don't care about the actual username, or the like. just that it passes validation. So I would look at sequences/traits/dependent attributes. So that you rely less on hardcoded data.

You can generate dynamic factories by using sequence

factory :user do
  sequence(:name) { |n| "person#{n}" }
  sequence(:date_of_birth) { |n| "#{n}".years.ago }
end

And if you want to generate birth date based on your validation, your can override the initial value used for sequence

sequence(:date_of_birth, 15) { |n| "#{n}".years.ago }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top