2011-11-23 3 views
2

こんにちはレールとモック以下のクラスを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

。私はRailsの '未定義のメソッド 'stub_chain'を得る:Module(NoMethodError)' – tamouse

1

これらのスタブがリンクされていないので、スタブがうまくいきませんでした実際のコード。 OPのために

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 

:それは、代わりにこのようにする必要があり、あなただけのログに期待を設定したい場合は、すべての全体ロガークラスをスタブする必要はありません。あなただけの

Rails.logger.should_receive(:debug) 

ボーナスを行うことができます:あなたはちょうどそう何のロギングは行われませんスタブにしたい場合は、次の操作を行います。これは私のために動作しません

Rails.logger.stub(:add){ true } 
関連する問題