Validation failed: Username has already been taken, Email has already been taken #419

Closed
darthdeus opened this Issue Aug 3, 2012 · 4 comments

Comments

Projects
None yet
3 participants

I have a following factory

FactoryGirl.define do
  factory :user do
    sequence(:username) { |n| "foo#{n}"}
    password "secret"
    email { "#{username}@example.com"}
  end
end

with unique validation on username and email.

The problem is, that sometimes I get errors that the username and email was already taken. It looks like this is some kind of a race condition.

What could be causing this?

mpugach commented Aug 8, 2012

Could you provide some more code (models, tests, etc.), please?

In case of Rails with RSpec:
Try 'bundle exec rake db:test:prepare' in console and add 'after(:all) {User.destroy_all}' to your test.

Owner

joshuaclayton commented Aug 31, 2012

Closing due to inactivity; @darthdeus, when you get a chance, throw your spec/spec_helper.rb in a comment. My guess is that it has something to do with your database not being cleared out correctly after runs.

I use database_cleaner, but generally the problem with unique validation arises when the running tests are terminated in the middle, so I guess this isn't really an issue of factory girls, but rather database_cleaner not cleaning up.

Here's an example of a spec helper where this happens https://gist.github.com/3706282 ... Could using spork be causing this?

Owner

joshuaclayton commented Sep 12, 2012

If the specs are killed in a JS-backed test, you might have problems; you declare that the cleaning strategy is transactional but truncation is necessary for your tests using capybara-webkit. Additionally, you'll want to clear your database before the suite starts using truncation (which removes all data). @avdi wrote a great post about how to use database_cleaner effectively here: http://devblog.avdi.org/2012/08/31/configuring-database_cleaner-with-rails-rspec-capybara-and-selenium/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment