【问题标题】:Can FactoryGirl check to see of models already exist in the database before creating new ones?FactoryGirl 能否在创建新模型之前检查数据库中是否已存在模型?
【发布时间】:2011-12-17 23:16:57
【问题描述】:

我有以下出厂设置:

FactoryGirl.define do

  factory :country do |f|
    f.name "USA"
    f.country_code "USA"
    f.currency_code "USD"
  end

  factory :region do |f|
    f.name "East Coast"
    f.country {Country.first}
  end

  factory :state do |f|
    f.name 'CA'
    f.region {Region.first}
    f.country {Country.first}
  end 

end

我想在地区和州工厂做的是检查国家/地区的数据库中是否已经存在一个条目,如果是,则使用该条目,并且只有在没有找到条目时才创建一个新模型。

这是我想到的一个示例,但不确定如何创建:

factory :state do |f|
  f.name 'CA'
  f.region {Region.first || Factory(:region}
  f.country {Country.first || Factory(:state}
end 

我想这样做的原因是将条目注入到我的数据库中,这将填充表单选择字段 & 以便我可以使用 cucumber 进行测试。

【问题讨论】:

  • 你为什么要这样做?我想不出这样做的充分理由
  • 因为我的数据库模式状态无法保存,除非地区和国家条目已经存在。我需要至少 3 个州模型进行测试,但只想为地区和国家插入一行。

标签: ruby-on-rails ruby unit-testing factory-bot


【解决方案1】:

您可以使用回调来完成此操作:

FactoryGirl.define do

  factory :country do |f|
    f.name          "USA"
    f.country_code  "USA"
    f.currency_code "USD"
  end

  factory :region do |f|
    f.name "East Coast"
    after_build {|r| r.country = (Country.first || Factory(:country))}
  end

  factory :state do |f|
    f.name 'CA'
    after_build do |s|
      s.region  = Region.first  || Factory(:region)
      s.country = Country.first || Factory(:country)
    end
  end 

end

【讨论】:

    【解决方案2】:

    我认为您需要关联。 每个 :region belongs_to :state 和每个 :state belongs_to :country 这反过来又带来了许多州和地区。

    然后您可以在您的工厂中使用这些关联。

    查看入门指南:https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-14
      • 2016-11-30
      • 2018-03-02
      • 1970-01-01
      • 2019-12-05
      • 2019-05-15
      • 1970-01-01
      • 2017-12-21
      相关资源
      最近更新 更多