4

Hi I and trying to rspec mock the following class:

    class Person
      def initialize(personid)
        Rails.logger.debug "Creating person with id #{personid}"
      end
    end

Using this:

require 'spec_helper'
  describe Person do
    describe "#initialize" do
      let(:rails_mock) { double("Rails").as_null_object }
      let(:logger_mock) { double("Rails.logger").as_null_object }

      it "logs a message" do
        rails_mock.stub(:logger).and_return(logger_mock)
        logger_mock.should_receive(:debug)
        Person.new "dummy"
      end
   end
end

and getting this message:

RSpec::Mocks::MockExpectationError: (Double "Rails.logger").debug(any args)
expected: 1 time
received: 0 times

Any help would be great!

3 Answers 3

8

I'd do:

Rails.stub_chain(:logger, :debug).and_return(logger_mock)

Don't forget do unstub at the end of your test:

Rails.unstub(:logger)
Sign up to request clarification or add additional context in comments.

1 Comment

This does not work for me. I get undefined method 'stub_chain' for Rails:Module (NoMethodError)
5

Here is an updated answer to this using partial double:

let(:personid) { 'dummy' }

before do
  allow(Rails.logger).to receive(:debug).and_return nil
  Person.new(personid)
end

it { expect(Rails.logger).to have_received(:debug).with(a_string_matching(personid)) }

No need to "unstub" anything, RSpec does it for you.

Comments

1

The stub did not work because those stubs aren't linked to the real code. It should be like this instead:

require 'spec_helper'
  describe Person do
    describe "#initialize" do
      let(:logger_mock) { double("Rails.logger").as_null_object }

      it "logs a message" do
        Rails.stub(:logger).and_return(logger_mock)
        logger_mock.should_receive(:debug)
        Person.new "dummy"
      end
   end
end

For OP: if you just want to set expectation on logging, you don't need to stub the whole logger class at all. You can just do

Rails.logger.should_receive(:debug)

Bonus: if you just want to stub so no logging will occur, do this:

Rails.logger.stub(:add){ true }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.