Reputation: 1696
Factories are defined in multiple files under /factories/
or in the factories.rb
file
spec/factories/*.rb
spec/factories.rb
The model customer test needs the customer
factory. This factory has a foreign key pointing to an address
factory.
/spec/factories.rb
spec/factories/customer.rb
Now if i run
rspec spec/model/customer_spec.rb
i get the following error
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 tries to build the customer factory first and failes because of the missing entry in the address table.
How can i avoid these dependency issues? Can i somehow define to build some basic factories first ?
Upvotes: 0
Views: 571
Reputation: 102036
I would really be consistent and use one file per factory (model) for consistency. Don't make others dig around.
# 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
All you need to do is reference the address
factory from customer. And factory_girl will create the associated record.
Upvotes: 2
Reputation: 112
Have you tried adding association :address
to the customer
factory? It would be easier to help if you showed your customer
and address
factories.
Upvotes: 1