rspec / rspec-mocks

RSpec's 'test double' framework, with support for stubbing and mocking
https://rspec.info
MIT License
1.16k stars 357 forks source link

`stack level too deep` when stubbing :is_a? with allow_any_instance_of #1565

Closed tatzsuzuki closed 6 months ago

tatzsuzuki commented 6 months ago

Subject of the issue

The error "stack level too deep" occurs when stubbing :is_a? with allow_any_instance_of.

Your environment

Steps to reproduce

stub_is_a_spec.rb
describe '`stack level too deep` when stubbing :is_a? ' do
  let(:klass) do
    Class.new do
      def a
        is_a?(self)
      end
    end
  end

  before { allow_any_instance_of(klass).to receive(:is_a?).and_return(true) }

  it { expect(klass.new.a).to be(true) }
end

Expected behavior

The spec should pass.

Actual behavior

% rspec stub_is_a_spec.rb
Failures:

  1) AccountsProduction::AppSwitcherRequester 
     Failure/Error: is_a?(self)

     SystemStackError:
       stack level too deep

The stack is recursively called at this line of code obviously. https://github.com/rspec/rspec-mocks/blob/v3.12.6/lib/rspec/mocks/proxy.rb#L38

I don't encounter the error if I initialize the class and utilize the instance generated.