2011-11-23 144 views
2

我喜并试图RSPEC模拟以下类:如何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

任何帮助将是伟大的!

回答

4

我会怎么做:

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

不要忘记在测试结束做unstub:

Rails.unstub(:logger) 
+0

这并不为我工作。我得到了'未定义的方法'stub_chain'for Rails:Module(NoMethodError)' – tamouse

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 }