Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 353
chintanparikh Avatar asked May 22 '13 17:05

chintanparikh


People also ask

What does Factory Girl Do?

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.


1 Answers

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
like image 116
Mike Manfrin Avatar answered Sep 16 '22 14:09

Mike Manfrin