FactoryGirl 在创建新模型之前可以检查数据库中是否已存在模型吗?

Jas*_*son 5 ruby unit-testing ruby-on-rails factory-bot

我有以下工厂设置:

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

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

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

factory :state do |f|
  f.name 'CA'
  f.region {Region.first || Factory(:region}
  f.country {Country.first || Factory(:state}
end 
Run Code Online (Sandbox Code Playgroud)

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

cod*_*ory 5

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

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


thr*_*ree 0

我认为你需要协会。每个 :region 属于_to :state 和每个 :state 属于_to :country 都有许多州和地区。

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

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