gpt4 book ai didi

rspec - 如果在描述 block 中调用,为什么工厂女孩会创建重复项

转载 作者:行者123 更新时间:2023-12-03 21:38:13 26 4
gpt4 key购买 nike

我正在使用 Factory Girl 和 Faker 来创建独特的测试用户。
用户模型对电子邮件进行了唯一性验证。

如果我嵌套 2 个级别的 describe 块,那么一些测试将失败,因为有重复的电子邮件。
如果我不嵌套描述块,那么所有工厂调用都会返回唯一的用户并且测试通过。

为什么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

最佳答案

把我的头撞在 table 上几个小时后,我的同事找到了答案:

Why isn't factory_girl operating transactionally for me? - rows remain in database after tests

结果证明这些工厂不是交易性的。在spec_helper.rb 的以下行之后,问题消失了:

config.use_transactional_fixtures = true

关于rspec - 如果在描述 block 中调用,为什么工厂女孩会创建重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17350710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com