ruby-on-railsrubyruby-on-rails-5rspec3

Rspec before validation issues


Im trying to write some tests to check before validation of a model in 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

here is my 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

Im trying to test the rescue block and my test always passes. I'm not able to override my subject and i dont know what is the mistake im doing.

Thanks in advance


Solution

  • I stubbed the code which raises the exception and it worked.

    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