工厂在/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尝试首先构建客户工厂,并因地址表中缺少条目而失败。
我如何避免这些依赖性问题?我能以某种方式定义先建立一些基础工厂吗?
答案 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
工厂?如果您展示了customer
和address
工厂,那么帮助会更容易。