Is it possible to use an if statement in a factory (FactoryGirl)?
Asked Answered
E

1

6

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?

Evitaevitable answered 22/5, 2013 at 17:43 Comment(1)
This seems like undesirable behavior. Your test suite should do exactly the same thing every time it runs, and shouldn't have any randomness. If anything, you probably want 2 separate tests here, that test each branch of logic.Deprecate
S
1

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
Selfsacrifice answered 23/10, 2013 at 21:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.