2011-04-05 67 views
12

这是我的工厂女孩​​的代码,并且每次我尝试生成审查,它告诉我“电子邮件已被采取”,我已重置我的数据库,将spec_helper中的转换设置为true,但仍未解决问题。我是新手,我是否使用关联错误?谢谢!铁轨工厂女孩得到“电子邮件已被采取”

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 

回答

11

你需要使用一个序列,以防止用户对象的创建与相同的电子邮件,因为你必须有电子邮件在您的用户模型中的唯一性验证。

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 

你可以在Factory Girl documentation了解更多。

+0

非常感谢,解决了问题! – randomor 2011-04-05 06:05:12

33

我知道这是一个相当古老的问题,但接受的答案已过时,所以我想我应该发布这样做的新方法。

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

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

来源:Documentation

这是相当简单一点,这是很好的。

7

除了上面的答案,您可以将gem 'faker'添加到您的Gemfile中,它将提供独特的电子邮件。

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

这里的重要细节是将Faker生成器置于括号{}中,就像例子'email {Faker :: Internet.email}'中的那样'',因为没有它们就无法运行,并且会引发相同的错误。 – juliangonzalez 2017-03-21 00:06:45

2

sequence给人非常独特的电子邮件和Faker给随机密码。

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