RSpec ActiveRecord :: RecordInvalid:验证失败:尽管在FactoryBot中有序列,但已经收到电子邮件

时间:2018-06-09 14:17:37

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

我的Rails应用程序中有一个名为“availabilitysilities”的模型,允许供应商设置其可用性(即他们的工作时间)。因此,可用性属于供应商和属于用户,用户拥有多家供应商,供应商拥有多种可用性。

我一直在尝试为我的可用性#destroy action创建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

如何收集电子邮件?有什么可以解释这个错误?

1 个答案:

答案 0 :(得分:0)

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