Rails FactoryGirl - 创建特定的工厂以满足 fk 依赖

Rails FactoryGirl - Create specific factories in order to meet fk dependancies

工厂在 /factories/ 下或 factories.rb 文件中的多个文件中定义

spec/factories/*.rb
spec/factories.rb

模型客户测试需要customer工厂。该工厂有一个指向 address 工厂的外键。

现在如果我运行

rspec spec/model/customer_spec.rb

我收到以下错误

postgresql_adapter.rb:602:in `exec_prepared': PG::ForeignKeyViolation:
ERROR:  insert or update on table "customers" violates foreign key constraint "fk_rails_580b7e1bd8" (ActiveRecord::InvalidForeignKey)
DETAIL:  Key (address_id)=(1) is not present in table "addresses".
: INSERT INTO "customers" ("date_of_birth", "created_at", "updated_at", , "female_household_members", "male_household_members", "pin_code", "national_id", ) VALUES (, , , , , , , , ) RETURNING "id"

FactoryGril 首先尝试构建客户工厂,但由于地址 table 中缺少条目而失败。

如何避免这些依赖性问题?我可以以某种方式定义先建造一些基本工厂吗?

您是否尝试过将 association :address 添加到 customer 工厂?如果您展示您的 customeraddress 工厂,会更容易提供帮助。

我真的会保持一致,并为每个工厂(模型)使用一个文件以保持一致性。不要让别人挖来挖去。

# spec/factories/addresses.rb
FactoryGirl.define do
  factory :address do
    # ...
  end
end

# spec/factories/customers.rb
FactoryGirl.define do
  factory :customer do
    association :address
    # or the short form
    address
  end
end

您需要做的就是参考客户的 address 工厂。和 factory_girl will create the associated record