2016-12-14 1 views
0

공장이 /factories/에서 여러 파일에 정의되어 FK 의존성을 충족하기 위해 또는 factories.rb 파일레일 FactoryGirl은 -

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

모델 고객 테스트가 customer 공장을 필요로 특정 공장을 만듭니다. 이 팩토리에는 address 팩토리를 가리키는 외래 키가 있습니다.

  • 주소 공장 /spec/factories.rb
  • 고객 공장에 정의되어 내가

    rspec spec/model/customer_spec.rb 
    

    내가 다음과 같은 오류가 실행하면 이제 spec/factories/customer.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

나는 일관성을 유지하기 위해 공장 (모델)마다 하나의 파일을 사용하고 싶습니다. 다른 사람들이 주위를 파고 들지 않도록하십시오.

# 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.

+0

물론 그렇습니다. 나는 빠른 테스트를 위해 값을 고치기 위해 fk를 설치했다 .- ...- 물론 이것은 다음과 같이 끝났다 :) 공장 당 하나의 파일은 훌륭한 팁 btw이다! – theDrifter

1

customer 공장에 association :address을 추가 했습니까? customeraddress 공장을 보여 주면 도움이 될 것입니다.

+0

예! – theDrifter