rails factory girl getting “Email has already been taken”

江枫思渺然 提交于 2019-12-04 16:52:38

问题


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                 "test@example.com"
  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

回答1:


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.




回答2:


I know this is a pretty old question, but the accepted answer is out of date, so I figured I should post the new way of doing this.

FactoryGirl.define do
  sequence :email do |n|
    "email#{n}@factory.com"
  end

  factory :user do
    email
    password "foobar"
    password_confirmation "foobar"
  end
end

Source: Documentation

It's quite a bit simpler, which is nice.




回答3:


In addition to the above answers you could add gem 'faker' to your Gemfile and it will provide unique emails.

FactoryGirl.define do
  factory :admin do
    association :band
    email { Faker::Internet.email }
    password "asdfasdf"
    password_confirmation "asdfasdf"
  end
end



回答4:


sequence gives really unique email and Faker gives random password.

FactoryGirl.define do
  sequence :email do |n|
    "user#{n}@test.com"
  end

  factory :user do
    email
    password { Faker::Internet.password(8, 20) }
    password_confirmation { "#{password}" }
  end
end


来源:https://stackoverflow.com/questions/5547730/rails-factory-girl-getting-email-has-already-been-taken

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!