I've got two traits in my factory, and I want one of them to be included when I create the object, without it defaulting to one (so randomly pick the trait). Here's what I'm doing:
FactoryGirl.define do
  factory :follow_up do
    first_name      { Faker::Name.first_name }
    last_name       { Faker::Name.last_name }
    phone           { Faker::PhoneNumber.cell_phone.gsub(/[^\d]/, '').gsub(/^1/, '2')[0..9] }
    email           { Faker::Internet.email }
    email_preferred true
    consent         false
    if [1, 2].sample == 1
      by_referral
    else
      by_provider
    end
    trait :by_referral do
      association :hospital
      association :referral
      source { FollowUp::REFERRAL}
    end
    trait :by_provider do
      association :provider
      source { FollowUp::PROVIDER }
    end
  end
end
However, it seems to be ignoring that if statement and going straight to by_provider trait. Anyone know how I'd do this?
Factory Girl provides a well-developed ruby DSL syntax for defining factories like user, post or any other object—not only Active Record objects. “Plain” Ruby classes are perfectly fine. You start by setting up a define block in your factories. rb file.
Use an ignore block.
FactoryGirl.define do
  factory :follow_up do
    text "text"
    author "Jim"
    ignore do
      if x == 1
        by_referral
      else 
        ...
      end
    end
  end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With