Home > Software design >  Class has leaked into another example and can no longer be used in spec
Class has leaked into another example and can no longer be used in spec

Time:04-13

I'm unable to replicate this locally, but for some reason I am getting the following error when running tests in CircleCi:

<Double Mylogger> was originally created in one example but has leaked into another example and can no longer be used. rspec-mocks' doubles are designed to only last for one example, and you need to create a new one in each example you wish to use it for.

Here is a simplified version of my code:

# frozen_string_literal: true
describe 'my_rake_task' do
  let(:my_log) { Mylogger.new }

  subject { Rake::Task['my_rake_task'].execute }

  describe 'one' do
    context 'logs' do
      let(:logs) do
        [
          ['My message one'],
          ['My message two'],
        ]
      end

      after { subject }

      it 'correctly' do
        logs.each { |log| expect(my_log).to receive(:info).with(*log) }
      end
    end
  end

  describe 'two' do
    context 'logs' do
      let(:logs) do
        [
          ['My message three'],
          ['My message four'],
        ]
      end

      after { subject }

      it 'correctly' do
        logs.each { |log| expect(my_log).to receive(:info).with(*log) }
      end
    end
  end
end

Why is it saying MyLogger is a double? Why would it be leaking?

CodePudding user response:

The reason that the error is saying that MyLogger is a double is because it is one. When you call expect(my_log).to receive or allow(my_log).to receive, you transform the instance into a partial-double.

As for why my_log is leaking: it's impossible to tell from the code that you posted. In order to cause a leak, some code either in your rake task or in the spec itself would need to be injecting my_log into some global state, like a class variable.

  • Related