这绝对是可能的——事实上,甚至有一种方法可以做到这一点!只需在开始记录之前的代码中添加以下内容:
set_trace_func proc { |event, file, line, id, binding, classname|
printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
}
你想要的秘方来自100,如上所述:
- set_trace_func(proc) => proc
- set_trace_func(nil) => nil
将proc
设置为跟踪的处理程序,如果参数为nil
,则禁用跟踪.proc
最多包含六个参数:事件名称、文件名、行号、对象id、绑定和类名称.proc
在事件发生时被调用.事件包括:c-call
(调用C语言 routine )、c-return
(从C语言 routine 返回)、call
(调用Ruby方法)、class
(启动类或模块定义)、end
(完成类或模块定义)、line
(在新行上执行代码)、raise
(引发异常)和return
(从Ruby方法返回).在proc上下文中禁用跟踪.
下面是一个简单的例子:
class Test
def test
a = 1
b = 2
end
end
set_trace_func proc { |event, file, line, id, binding, classname|
printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
}
t = Test.new
t.test
(注意:除非你想要一个巨大的文本滚动屏幕,否则不要在irb
中try .)结果是:
line test.rb:11 false
c-call test.rb:11 new Class
c-call test.rb:11 initialize Object
c-return test.rb:11 initialize Object
c-return test.rb:11 new Class
line test.rb:12 false
call test.rb:2 test Test
line test.rb:3 test Test
line test.rb:4 test Test
return test.rb:4 test Test
您可以使用上面的格式化字符串来获得想要记录的结果(例如,听起来您只对call
个事件感兴趣).希望这会有所帮助,祝你好运,顺利完成所有的单元测试!