簡體   English   中英

如何 rspec 模擬 ruby​​ rails 記錄器類

[英]How to rspec mock ruby rails logger class

嗨,我並試圖 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: (雙"Rails.logger").debug(任何參數)
預計:1次
收到:0次

任何幫助都會很棒!

我會做:

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

不要忘記在測試結束時取消存根:

Rails.unstub(:logger)

這是使用部分雙精度對此的更新答案:

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 為您完成。

存根不起作用,因為這些存根沒有鏈接到真正的代碼。 它應該是這樣的:

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 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM