Rails 中与 FactoryBot 的关联:验证失败

Associations with FactoryBot in Rails: Validation Failed

我的位置工厂中有以下内容:

FactoryBot.define do
  factory :location do
   name 'MyString'
   hours_operation 'MyString'
   abbreviation 'MyString'
   address_1 'MyString'
   address_2 'MyString'
   city 'MyString'
   state 'MyString'
   postal_code 1
   phone 'MyString'
   fax 'MyString'
   association :region
 end
end

我所在地区的工厂有以下产品:

FactoryBot.define do
  factory :region do
    name 'MyString'
   end
 end

区域has_many位置和位置belongs_to区域。

但是在我的测试中,我一直收到验证失败:区域必须存在。

我试过以下方法:

after(:create) do |location, _evaluator|
 create_list(:region, evaluator.region, location: location)
end

association :region, factory: region

before(:create) do |region|
  region.location << FactoryBot.build(:location, region: region)
end

我也在地区工厂试过:

factory :region_with_location do
  after(:create) do |region|
   create(:location, region: region)
   end
end

工厂位置:

association :region, factory: :region_with_location

在每种情况下,我仍然不断收到:验证失败:区域必须存在。

因为Locationbelongs_toRegion,在构建保存Location之前,必须在测试数据库中创建一个Region实例。这就是为什么您的代码在这里不起作用的原因,正如@Niklas 所说:

after(:create) do |location, _evaluator|
 create_list(:region, evaluator.region, location: location)
end

您可以做相反的事情:在创建区域后通过关联构建位置列表。

FactoryGirl.define do
  factory :region do
    name 'MyString'

  factory :region_with_locations do
    transient do
      locations_count 5
    end

    after(:create) do |region, evaluator|
      create_list(:location, evaluator.locations_count, region: region)
    end
  end
end

您还可以考虑使用 before(:create) callback 创建区域,然后再将其分配给某个位置。