Rails 工厂女孩收到“电子邮件已被占用”
这是我的工厂女孩代码,每次我尝试生成评论时,它都会告诉我“电子邮件已被占用”,我已经重置了数据库,将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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我知道这是一个相当老的问题,但接受的答案已经过时了,所以我想我应该发布新的方法。
来源:文档
它相当简单,这很好。
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.
Source: Documentation
It's quite a bit simpler, which is nice.
您需要使用序列来防止创建具有相同电子邮件的用户对象,因为您必须验证用户模型中电子邮件的唯一性。
您可以在Factory Girl 文档中阅读更多信息。
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.
You can read more in the Factory Girl documentation.
除了上述答案之外,您还可以将
gem 'faker'
添加到您的 Gemfile 中,它将提供唯一的电子邮件。In addition to the above answers you could add
gem 'faker'
to your Gemfile and it will provide unique emails.sequence
提供真正独特的电子邮件,Faker
提供随机密码。sequence
gives really unique email andFaker
gives random password.Random.hex(4)
,否则您将遇到同样的问题。Random.hex(4)
otherwise you will run into the same problem.由于某种原因,
password_confirmation
字段对我不起作用。有效的方法是这样的:请注意,如果您不使用 Faker,您可以使用像 `password { "password" } 这样简单的内容来代替该行。
For some reason the
password_confirmation
field wasn't working for me. What worked was this:Note that if you're not using Faker, you can have something as simple as `password { "password" } instead of that line.