Duplicate entry for index with FactoryGirl when running tests
Asked Answered
M

1

6

I am using FactoryGirl to create a "Specialty" model that has a unique index on the code column.

When I create multiple 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's the right way to deal with this? How come the index associated with the model is not blown away with the model. I am using DatabaseCleaner.

Martie answered 21/8, 2011 at 0:33 Comment(0)
A
3

Add a sequence for your factories:

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

And at your specialty factory 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.

Achondrite answered 21/8, 2011 at 2:56 Comment(1)
I have a certain number of specialties. It's quite likely that no more will be added to the database. Should I put the stuff in a seeds.rb? If so then how would I use factory girl to associate unique specialties to prevent the same mysql error?Martie

© 2022 - 2024 — McMap. All rights reserved.