如何使用rspec模拟Ruby Rails记录器类

问题描述 投票:2回答:3

嗨,我正尝试rspec模拟以下类:

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

使用此:

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

并获得此消息:

RSpec :: Mocks :: MockExpectationError:(Double“ Rails.logger”)。debug(任何参数)预期:1次收到:0次

任何帮助都会很棒!

ruby-on-rails ruby logging rspec mocking
3个回答
6
投票
我愿意:

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

不要忘记在测试结束时取消存根:

Rails.unstub(:logger)


1
投票
存根不起作用,因为这些存根未链接到实际代码。应该是这样的:

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


对于OP:如果只想设置日志记录的期望值,则根本不需要存根整个记录器类。你可以做

Rails.logger.should_receive(:debug)


奖金:如果您只想存根,这样就不会发生任何日志记录,请执行此操作:

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


0
投票
这里是使用局部双精度的最新答案:

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)) }

不需要“解压”任何东西,RSpec可以帮您完成。
© www.soinside.com 2019 - 2024. All rights reserved.