代码之家  ›  专栏  ›  技术社区  ›  swilliams

rspec activerecord::recordinvalid:验证失败:尽管factorybot中有序列,但电子邮件已被接收

  •  0
  • swilliams  · 技术社区  · 8 年前

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

    我一直在尝试为我的可用性创建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: 验证失败:电子邮件已被接收“

    但是,我将工厂bot用于我的工厂,并让我的用户工厂按顺序运行(见下文):

    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 回复  |  直到 8 年前
        1
  •  0
  •   vinibrsl    8 年前

    Faker sequence

    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