如何RSpec模拟红宝石Rails记录器类 [英] How to rspec mock ruby rails logger class

查看:75
本文介绍了如何RSpec模拟红宝石Rails记录器类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试rspec模拟以下类:

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

使用此:

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次

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

任何帮助都会很棒!

推荐答案

我愿意:

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

别忘了在测试结束时取消存根:

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

Rails.unstub(:logger)

这篇关于如何RSpec模拟红宝石Rails记录器类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆