如何使用Test :: Unit模拟Rails测试中的Logger?

时间:2012-07-10 14:44:59

标签: ruby-on-rails unit-testing mocking functional-testing

在test_helper中:

class Logger
    @@log = []

  def self.info(message)
    @@log.push(message)
  end

  def self.log
    @@log
  end
end

但是在运行测试时,它似乎使用常规的Logger。

如何为Logger创建模拟?

Rails 3.0.7。

3 个答案:

答案 0 :(得分:5)

我建议更好的策略是使用mocha来模拟rails logger

class TestLogCase < ActiveSupport::TestCase

  require 'mocha/mini_test'

  test "records the log" do
    Rails.logger.expects(:info).with('My message')
    Rails.logger.info "My Message"
  end 

end

答案 1 :(得分:1)

您需要将您的记录器分配给Rails.logger for Rails才能使用它...为了完全实现记录器,您需要实现所有方法http://www.ruby-doc.org/stdlib-1.9.3/libdoc/logger/rdoc/Logger.html(即#debug,#warn, #error,#fatal)

ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")

class Logger
    @@log = []

  def self.info(message)
    @@log.push(message)
  end 

  def self.log
    @@log
  end 
end


class TestLogCase < ActiveSupport::TestCase
  def setup
    Rails.logger = Logger
  end 

  test "records the log" do
    Rails.logger.info "My Message"
    assert_true Logger.log.include?("My Message")
  end                                                                                                                         
end

答案 2 :(得分:0)

使用摩卡咖啡

  before do
    logger = mock
    MyModel.any_instance.stubs(:logger).returns(logger)
    logger.stubs(:debug).returns(true)
  end