vendredi 1 janvier 2021

Rspec expectation triggering twice

Getting some odd behavior when testing a custom class in Rspec (version 3.9)

Code

class AlertMaster
    def initialize(params = {})
        ...
    end

    def send_alert
        1.upto(2) do |attempt|
            begin
                self.alert_me
                break
            rescue => e
                if attempt == 2
                    puts ">> here"
                    puts attempt
                    Rails.logger.fatal "Alert error - #{e.message}"
                end
            end
        end
    end
end

RSpec

    describe "send_alert" do
        before do
            @at = AlertMaster.new
        end
        describe "catches appropriately" do
            describe "first time succeeds" do
                it "should not log error" do
                    expect(@at).to receive(:alert_me).and_return(true)
                    expect(Rails.logger).to_not receive(:fatal)

                    @at.send_alert
                end
            end

            describe "first time fails, second time succeeds" do
                it "should not log error" do
                    expect(@at).to receive(:alert_me).and_raise("oops")
                    expect(@at).to receive(:alert_me).and_return(true)
                    expect(Rails.logger).to_not receive(:fatal)

                    @at.send_alert
                end
            end

            ####### FAILING SPEC
            describe "first time fails, second time fails" do
                it "should log error" do
                    expect(@at).to receive(:alert_me).and_raise("oops")
                    expect(Rails.logger).to receive(:fatal).with("Alert error - oops")

                    @at.send_alert
                end
            end
        end
    end

The last spec fails because Rails.logger is called twice. Console log shows the puts statements I put in correctly only trigger on last attempt. Failing spec output:

>> here
2

...

Failure/Error: expect(@at).to receive(:alert_me).and_raise("oops")
     
       (#<AlertMaster:0x00007ffca7edd180 ...).alert_me(*(any args))
           expected: 1 time with any arguments
           received: 2 times with any arguments

Aucun commentaire:

Enregistrer un commentaire