【问题标题】:RSpec ActiveRecord::RecordInvalid: Validation failed: Email has already been taken despite having sequence in FactoryBotRSpec ActiveRecord::RecordInvalid:验证失败:尽管在 FactoryBot 中有序列,但电子邮件已被接收
【发布时间】:2018-06-09 14:17:36
【问题描述】:

我的 Rails 应用程序中有一个名为“可用性”的模型,它允许供应商设置他们的可用性(即他们的工作时间)。因此,可用性分为供应商和用户,并且用户拥有_许多供应商和供应商拥有_许多可用性。

我一直在尝试为我的可用性#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 时出错。 失败/错误:user = FactoryBot.create(:user)

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

电子邮件怎么可能被取走?什么可以解释这个错误?

【问题讨论】:

  • 能否请您展示您的模型?
  • @Pavling 所说的可能是这种情况,但也许您可以在创建代码之前执行binding.pry 并执行Avalability.all 只是为了检查。如果是数据库没有被清除,我用来清除数据库的gem是database_cleaner

标签: ruby-on-rails ruby rspec ruby-on-rails-5 rspec-rails


【解决方案1】:

我建议您将 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

【讨论】:

  • 感谢您的回答!我试过这个。但是,我现在收到此错误:An error occurred while loading: ./spec/controllers/availabilities_controller_spec.rb. Failure/Error: sign_in user sign_in` 在示例组中不可用(例如 describecontext 块)。它只能从单个示例(例如 it 块)或在示例范围内运行的构造(例如 beforelet 等)中获得。测试,我所有的其他 30 项测试都通过了。我不确定我哪里出错了:/
猜你喜欢
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多