Search code examples
ruby-on-railsfactory-bot

rails factory girl getting "Email has already been taken"


This is my factory girl code, and every time I try to generate a review, it's telling me that "Email has already been taken", i've reset my databases, set the transition in spec_helper to true, but still haven't solved the problem. I'm new to this, am I using the association wrong? Thanks!

Factory.define :user do |user|
  user.name                  "Testing User"
  user.email                 "[email protected]"
  user.password              "foobar"
  user.password_confirmation "foobar"
end

Factory.define :course do |course|
  course.title "course"
  course.link "www.umn.edu"
  course.sections 21
  course.description "test course description"
  course.association :user
end

Factory.define :review do |review|
  review.title "Test Review"
  review.content "Test review content"
  review.association :user
  review.association :course
end

Solution

  • You need to use a sequence to prevent the creation of user objects with the same email, since you must have a validation for the uniqueness of emails in your User model.

    Factory.sequence :email do |n|
      “test#{n}@example.com”
    end
    
    Factory.define :user do |user|
      user.name "Testing User"
      user.email { Factory.next(:email) }
      user.password "foobar"
      user.password_confirmation "foobar"
    end
    

    You can read more in the Factory Girl documentation.