Rspec 验证问题之前

Rspec before validation issues

我正在尝试编写一些测试以在 rspec

中验证模型之前进行检查
class MyClass < ApplicationRecord
    before_validation :generate_anonymous_id
  
    def generate_anonymous_id
      retries ||= 1
      self.uuid = SecureRandom.uuid
      self.aid = Digest::SHA256.hexdigest(uuid)[0...15]
      raise ActiveRecord::RecordNotUnique if OtherClass.find_by_sfid(aid) ||
                                             MyClass.find_by_aid(aid)
    rescue ActiveRecord::RecordNotUnique => error
      Rails.logger.warn("Encountered duplicate uuid/aid")
      retries += 1
      retry if retries <= 3
      Rails.logger.warn("Raising exception after 3 retries")
      raise error
    end
end

这是我的 rspec

# frozen_string_literal: true

require "rails_helper"

RSpec.describe MyClass, type: :model do
  describe "model validation" do
    let(:my_class) do
      MyClass.create
    end

    context "valid" do
      it "allows to create a user aid" do
        expect(MyClass.new.valid?).to be_truthy 
      end
    end

    context "duplicate" do
      subject do
        MyClass.new
      end

      it "allows to create a user aid" do
        subject.uuid = my_class.aid
        expect(subject.valid?).to be_falsey
      end
    end
  end
end

我正在尝试测试救援块,我的测试总是通过。我无法覆盖我的主题,我不知道我在做什么错误。

提前致谢

您的 before_validation 覆盖了 subject.uuid,这在您调用 subject.valid? 时发生,即 generate_anonymous_id 强制它有效

我标记了引发异常的代码并且它起作用了。

context "invalid record" do
  context "capture exception" do
    let!(:user) { create(:custom_user) } 
    before { allow(UserUuid).to receive(:find_by_sfid).and_return(true)}
    subject { described_class.new}
    
    it "raises exception" do
      expect { subject.valid? }.to raise_error(ActiveRecord::RecordNotUnique)
    end
  end
end