是否可以在工厂(FactoryGirl)中使用if语句?

chi*_*ikh 6 conditional ruby-on-rails factory-bot

我在我的工厂里有两个特性,我希望在创建对象时包含其中一个特征,而不是默认为一个(因此随机选择特征).这是我正在做的事情:

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
Run Code Online (Sandbox Code Playgroud)

但是,它似乎忽略了if语句并直接转向by_provider trait.谁知道我怎么做?

Mik*_*rin 1

使用忽略块。

FactoryGirl.define do
  factory :follow_up do
    text "text"
    author "Jim"

    ignore do
      if x == 1
        by_referral
      else 
        ...
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)