gpt4 book ai didi

ruby-on-rails - 如何 rspec 模拟 ruby​​ rails 记录器类

转载 作者:数据小太阳 更新时间:2023-10-29 08:28:49 25 4
gpt4 key购买 nike

嗨,我正在尝试 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(any args)
expected: 1 time
received: 0 times

任何帮助都会很棒!

最佳答案

我会:

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

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

Rails.unstub(:logger)

关于ruby-on-rails - 如何 rspec 模拟 ruby​​ rails 记录器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8249815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com