RSpec ActiveRecord::RecordInvalid:验证失败:尽管在 FactoryBot 中有序列,但电子邮件已被占用

RSpec ActiveRecord::RecordInvalid: Validation failed: Email has already been taken despite having sequence in FactoryBot

我的 Rails 应用程序中有一个名为 "availabilities" 的模型,允许供应商设置他们的可用性(即他们的工作时间)。因此,可用性 belong_to 供应商和 belong_to 用户,以及用户 has_many 供应商和供应商 has_many 可用性。

我一直在尝试为我的可用性#destroy 操作创建 Rspec 测试。我参考的具体测试是:

#spec/controllers/availabilities_controller_spec.rb
require 'rails_helper'

RSpec.describe AvailabilitiesController, type: :controller do

  describe "availabilities#destroy action" do

    it "should allow a user who created the availability to destroy it"
      availability = FactoryBot.create(:availability) 
      sign_in availability.user
      delete :destroy, params: { id: availability.id, vendor_id: availability.vendor_id}
      availability = Availability.find_by_id(availability.id)
      expect(availability).to eq nil
   end 
  end
end

然而,当我 运行 这个测试时,我收到以下错误:

“加载 ./spec/controllers/availabilities_controller_spec.rb 时发生错误。 Failure/Error: 用户 = FactoryBot.create(:用户)

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

但是,我为我的工厂使用工厂机器人,我让我的用户工厂以 运行 作为序列(见下文):

FactoryBot.define do
  factory :user do
    sequence :email do |n|
      "dummyEmail#{n}@gmail.com"
    end
    password "secretPassword"
    password_confirmation "secretPassword"
    confirmed_at Time.now
  end
end

怎么邮箱已经被占用了?什么可以解释这个错误?

我建议您将 Faker 与 FactoryBot 一起使用。它将为您提供更大的灵活性,并消除执行此 sequence 技巧的需要。 Faker 轻松生成假数据。

无论如何,请在每次测试后使用database_cleaner清理您的测试环境数据库。您只需将其设置为:

# ./spec/rails_helper.rb

# start by truncating all the tables but then use the faster transaction strategy the rest of the time.
config.before(:suite) do
  DatabaseCleaner.clean_with(:truncation)
  DatabaseCleaner.strategy = :transaction
end

# start the transaction strategy as examples are run
config.around(:each) do |example|
  DatabaseCleaner.cleaning do
    example.run
  end
end