Rails FactoryGirl-创建特定的工厂以满足FK依赖关系



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

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

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

  • 地址工厂在/spec/factories.rb中定义
  • 客户工厂在spec/factories/customer.rb中定义

现在如果我运行

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 ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id"

FactoryGril试图首先建造客户工厂,并且由于地址表中缺少条目而失败。

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

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

# 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将创建关联的记录。

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

最新更新