Duplicate entry for index with FactoryGirl when running tests

I use FactoryGirl to create a "Specialty" model that has a unique index in the column code.

When I create several factories of the "Specialty" model, I get this error:

Failure/Error: Factory(:specialty)
Mysql::Error: Duplicate entry 'AN00' for key 'index_specialties_on_code': INSERT INTO `specialties` (`code`, `name`) VALUES ('AN00', 'Name')
Duplicate entry 'AN00' for key 'index_specialties_on_code'

What is the right way to handle this? Why the index associated with the model is not reset with the model. I am using DatabaseCleaner.

+5
source share
1 answer

Add sequence for your plants:

Factory.sequence :code do |n|
  "AAA#{n}"
end

And for your factory specialty, use the sequence:

Factory.define :specialty do |f|
  f.code { Factory.next(:code) }
  # other assignments here
end

This way you will always have new codes.

+3

All Articles