我正在使用 Factory Girl 和 Faker 创建独特的测试用户。用户模型对电子邮件进行唯一性验证。
如果我嵌套 2 级描述块,那么一些测试将失败,因为有重复的电子邮件。如果我不嵌套描述块,那么所有工厂调用都会返回唯一用户并且测试通过。
为什么 Faker 在第一种情况下会生成重复的电子邮件?
#factories/user.rb
# a simple factory with Faker
FactoryGirl.define do
factory :student, class: User do
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
password { Faker::Lorem.words(3).join }
email { Faker::Internet.email }
end
end
#spec/models/user_spec.rb
# in this test structure, Faker returns duplicate emails
describe "nested describe blocks" do
describe "block 1" do
it "creates faker duplicates" do
10.times{
FactoryGirl.create(:student)
}
end
end
describe "block 2" do
it "creates faker duplicates" do
10.times{
FactoryGirl.create(:student)
}
end
end
end
# in this structure, Faker emails are unique
describe "no nested describe blocks" do
it "doesn't create duplicates" do
10.times{
FactoryGirl.create(:student)
}
end
it "doesn't create duplicates" do
10.times{
FactoryGirl.create(:student)
}
end
end
Rspec 返回以下错误:
Failure/Error: FactoryGirl.create(:student)
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken, Email has already been taken, Authentication token has already been taken