Kev*_*ite 2 ruby logging rspec ruby-on-rails mocking
嗨,我并尝试rspec模拟以下类:
class Person
def initialize(personid)
Rails.logger.debug "Creating person with id #{personid}"
end
end
Run Code Online (Sandbox Code Playgroud)
使用这个:
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
Run Code Online (Sandbox Code Playgroud)
并得到此消息:
RSpec :: Mocks :: MockExpectationError:(双倍“ Rails.logger”)。debug(任何参数)
预期:1次
收到:0次
任何帮助将是巨大的!
我会做:
Rails.stub_chain(:logger, :debug).and_return(logger_mock)
Run Code Online (Sandbox Code Playgroud)
不要忘记在测试结束时取消存根:
Rails.unstub(:logger)
Run Code Online (Sandbox Code Playgroud)
这是使用部分双精度对此的更新答案:
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)) }
Run Code Online (Sandbox Code Playgroud)
无需“取消存根”任何东西,RSpec 会为您完成。