我试图与FactoryGirl多个对象(拥有唯一电子邮件的访客)进行实例化
guests = create_list(:guest, 3)
但我得到错误:
Failure/Error: guests = create_list(:guest, 3)
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken
我的工厂:
FactoryGirl.define do
factory :guest do
email Faker::Internet.unique.email
firstname 'John'
lastname 'Doe'
password 'test'
password_confirmation 'test'
factory :guest_with_bookings do
email "#{SecureRandom.hex}@test.com"
transient do
bookings_count 2
end
after(:create) do |guest, evaluator|
create_list(:booking, evaluator.bookings_count, guests: [guest])
end
end
end
end
即使使用Faker :: Internet.unique.email,当我尝试创建超过1个访客时,它也无法正常工作
答案 0 :(得分:5)
在工厂中使用序列
FactoryGirl.define do
factory :guest do
sequence(:email) { |n| "name_#{n}@example.com" }
或与Faker结合使用
FactoryGirl.define do
factory :guest do
sequence(:email) { |n| Faker::Internet.unique.email("Nancy_#{n}") }