Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rspec mock ruby rails logger class

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!

like image 873
Kevin White Avatar asked Oct 25 '25 20:10

Kevin White


1 Answers

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)
like image 190
apneadiving Avatar answered Oct 27 '25 11:10

apneadiving