ActiveRecord::RecordInvalid: 验证失败:电子邮件已被占用

ActiveRecord::RecordInvalid: Validation failed: Email has already been taken

由于用户模型中的唯一性电子邮件验证,我的测试失败了。我可以通过简单地显式创建两个具有不同电子邮件属性的新用户来解决问题并使测试通过。但是下面的代码似乎也可以工作,但我不太清楚。

如果有人能帮助我理解其中的区别,我将不胜感激。工厂创建的用户 ct2 与 ct1 中的用户有何不同?

工厂

FactoryGirl.define do
  factory :classroom_template do
    association :user, factory: :student
    name "Intro to Github"
    description "Introduction Course to Github"
    ct_type "Self-paced"
  end
end

ClassroomTemplateTest.rb

it "must be ordered by name" do
  ct1 = FactoryGirl.create(:classroom_template)
  ct2 = FactoryGirl.build(:classroom_template, name: "Intro to Rails", user: ct.user)
  ct1.name.must_equal "Intro to Github"
  ct2.name.must_equal "Intro to Rails"
end

However the code below also seems to work but it's not quite clear to me

之所以有效,是因为下面的 ct2 还没有持久化!请使用 ct2.persisted? 检查,您正在内存中构建 ct2,验证尚未 运行!

ct2 = FactoryGirl.build(:classroom_template, name: "Intro to Rails", user: ct.user)

为了避免重复电子邮件,我在我的项目中使用了这个:

factory :user do
    sequence(:email) { |n| "user_#{n}@factory.com" }
    # Other attributes
end

这只是确保电子邮件的生成方式不同。