【问题标题】:Is it possible to use an if statement in a factory (FactoryGirl)?是否可以在工厂(FactoryGirl)中使用 if 语句?
【发布时间】:2013-05-17 21:26:12
【问题描述】:

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

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

但是,它似乎忽略了 if 语句并直接使用 by_provider 特征。有人知道我会怎么做吗?

【问题讨论】:

  • 这似乎是不受欢迎的行为。您的测试套件每次运行时都应该做完全相同的事情,并且不应该有任何随机性。如果有的话,您可能需要在这里进行 2 个单独的测试,分别测试每个逻辑分支。

标签: ruby-on-rails conditional factory-bot


【解决方案1】:

使用忽略块。

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

    ignore do
      if x == 1
        by_referral
      else 
        ...
      end
    end
  end
end

【讨论】:

    猜你喜欢
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 2021-08-21
    • 2020-01-08
    相关资源
    最近更新 更多