RSpec测试是否写入自定义Rails日志

时间:2013-03-11 15:03:01

标签: ruby-on-rails logging rspec

我正在尝试测试一种方法,该方法将基于条件的多条消息记录到默认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

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:0)

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

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