Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 307
randomor Avatar asked Apr 05 '11 05:04

randomor


4 Answers

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.

like image 66
Arel Avatar answered Nov 17 '22 13:11

Arel


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.

like image 42
Andrew Marshall Avatar answered Nov 17 '22 13:11

Andrew Marshall


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
like image 8
Michael Avatar answered Nov 17 '22 13:11

Michael


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(min_length: 8, max_length:20) }
    password_confirmation { "#{password}" }
  end
end
like image 5
askrynnikov Avatar answered Nov 17 '22 13:11

askrynnikov