2

我正在尝试测试一种方法,该方法根据条件将多条消息记录到不是默认 Rails 记录器的日志中。我将记录器格式化为config/environment.rb

# Format the logger
class Logger
  def format_message(level, time, progname, msg)
    "#{time.to_s(:db)} #{level} -- #{msg}\n"
  end
end

并在lib/目录的 ImportRecording 类中创建了一个新的记录器。该类的方法包括以下内容:

# some code omitted...
days.each do |day|
  if not hash[day].include? "copied"
    @log.error "#{day} needs to be copied!"
  end
  if not hash[day].include? "compressed"
    @log.error "#{day} needs to be compressed!"
  end
  if not hash[day].include? "imported"
    @log.debug "#{day} needs to be imported"
    `rake RAILS_ENV=#{Rails.env} recordings:import[#{day}]` unless Rails.env == "test"
  end
end
# finishing up logging omitted...

我写了一个小宏来帮助测试这个方法:

def stub_todo
  { "20130220" => ["copied"],
    "20130219" => ["copied", "compressed"],
    "20130218" => ["copied", "compressed", "imported"] }
end

这是我的测试:

describe ".execute_todo" do
  it "carries out the appropriate commands, based on the todo hash" do
    ImportRecording.execute_todo stub_todo
    ImportRecording.log.should_receive(:debug).with("20130219 needs to be imported")
    ImportRecording.log.should_receive(:error).with("20130220 needs to be compressed!")
    ImportRecording.log.should_receive(:debug).with("20130220 needs to be imported")
  end
end

我在运行这些测试时盯着导入日志并观察添加的行(有延迟,因为现在日志很大),但测试仍然失败。我想知道日志的格式是否搞砸了,但我上述字符串传递给方法:debug:error日志。有什么帮助吗?

编辑 3/14/13:

希望有人可以在这里帮助我,我通过测试更改为如下所示:

it "carries out the appropriate commands, based on the todo hash" do
  ImportRecording.stub!(:execute_todo).with(stub_todo).and_return(false)
  ImportRecording.log.should_receive(:debug).with("20130219 needs to be imported")
  ImportRecording.log.should_receive(:error).with("20130220 needs to be compressed!")
  ImportRecording.log.should_receive(:debug).with("20130220 needs to be imported")
end

这是我从 RSpec 得到的错误:

Failure/Error: ImportRecording.log.should_receive(:debug).with("20130219 needs to be imported")
  (#<Logger:0x007fb04fa83ed0>).debug("20130219 needs to be imported")
    expected: 1 time
    received: 0 times
4

2 回答 2

3

我发现了问题。不知何故,这些期望应该在实际导致它们的方法之前声明。代码应阅读

it "carries out the appropriate commands, based on the todo hash" do
  ImportRecording.log.should_receive(:debug).with("20130219 needs to be imported")
  ImportRecording.log.should_receive(:error).with("20130220 needs to be compressed!")
  ImportRecording.log.should_receive(:debug).with("20130220 needs to be imported")
  ImportRecording.execute_todo stub_todo
end

现在测试通过了。我还必须在测试中添加更多行,以说明由于方法调用而写入日志的每一行。因此,对于未来的研究人员,请陈述您的期望,然后调用该方法。

于 2013-03-26T23:54:36.617 回答
0

当我运行这些测试并观察添加的行时,我盯着导入日志

如果您在记录器调用上设置消息预期,则不应看到添加到日志中的行。与存根一样,消息期望取代了原始方法的实现。这表明您的记录器设置以某种方式配置错误。

于 2013-03-11T15:30:58.723 回答