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