定义的 STI 关系在 FactoryBot/lint 中失败

defined STI relationships fail in FactoryBot/lint

您好,我有以下3个型号:

位置 < 应用记录

暂存位置 < 位置

包 < 应用程序记录 belongs_to:位置

我可以通过简单地调用 StagingLocation 的工厂而不是 Location 来设置关联以创建有效的包工厂。根据以下代码:

package_spec.rb:

  describe "package validation" do
let(:package_location) { create(:staging_location) }
it "has a valid factory" do
  expect( create(:package, location: package_location) ).to be_valid
end

然而,这不会通过FactoryBot.lint

1. lint 在创建 Location

时抛出错误
FactoryBot.define do
  factory :location do
  type { "StagingLocation" }
  name { "Location" + Faker::GreekPhilosophers.unique.name }    
  end
end

抛出这个错误

The single-table inheritance mechanism failed to locate the subclass: '0'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Location.inheritance_column to use another column for that information. (ActiveRecord::SubclassNotFound)

2。调用 staging_location 工厂失败并显示

NoMethodError

因为包裹正在寻找位置

FactoryBot.define do
  factory :package do
    staging_location
    name { "TEST-" + rand(99).to_s }
  end
end

我看到了三种可能的方法来解决这个问题,但似乎无法找到 FactoryBot 语法来完成它们:

a) 创建位置工厂

b) 使用 base_class 方法或类似方法

创建一个 returns 位置 class 的 StagingLocation 工厂

c) 告诉包装工厂接受 staging_location 作为位置工厂

d) 忽略错误,因为在一天结束时,我的工厂正在按预期创建。

有什么建议吗?

根据 FactoryBot github 页面上的 this issue

可以通过在父工厂中声明子工厂并声明 STI 来定义 STI class。

在我的例子中,结果如下:

FactoryBot.define do
  factory :location, class: "StagingLocation" do
    name { "Staging " + rand(99).to_s }    
  end
end

FactoryBot.define do
  factory :package do
    name { "Package " + rand(99).to_s }    
    location { create(:staging_location, location: location) }
  end
end