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

时间:2016-12-14 11:48:12

标签: ruby-on-rails ruby ruby-on-rails-4 rspec factory-bot

工厂在/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尝试首先构建客户工厂,并因地址表中缺少条目而失败。

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

2 个答案:

答案 0 :(得分:2)

我确实会保持一致并且每个工厂(模型)使用一个文件以保持一致性。不要让别人去挖掘。

# 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

答案 1 :(得分:1)

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