Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get stack trace from a Test::Unit::TestCase

Tags:

ruby

testunit

I am testing some Ruby code and have a failing Test::Unit::TestCase. Unfortunately, the failure report only gives me the top error, not a full stack trace. Specifically, it says:

 1) Failure:
test_tp_make(TestScripts::TestTpMake) [test/test_scripts.rb:73]:
Exception raised:
<#<NoMethodError: undefined method `[]' for nil:NilClass>>.

The line number referenced (73) is the start of an assert_nothing_raised code block in my test case, which in turn starts another code block, which in turn calls in to a large library.

I have tried running the test with the --verbose flag, unfortunately this does not change the exception output. I tried consulting the Test::Unit documentation, but it does not seem to enumerate the available options (for example, there's nothing useful here). Searching the web and StackOverflow surfaced some answers on how to enable stack tracing in Rails, but this is non-Rails ruby code.

I could extract the failing code from the test and run it outside of Test::Unit, enabling me to see all the output. But it will be a pain to do this every time I have a failing test.

Does anyone know how to get Test::Unit to give me a full stack trace?

like image 818
Ryan Tate Avatar asked Feb 19 '12 02:02

Ryan Tate


2 Answers

Looking through the code of Test::Unit in Ruby 1.8, it seems all the errors go through the Test::Unit::Error object which filters the backtrace in its #long_display method. There is no configuration and all runners will use the same filtered trace.

Brute force monkey patch to get the whole trace: (I put this in my single test case file; perhaps you could put it in a test helper)

require 'test/unit/util/backtracefilter'

module Test::Unit::Util::BacktraceFilter
  def filter_backtrace(backtrace, prefix=nil)
    backtrace
  end
end

And monkey patch for Ruby 1.9 (which uses minitest)

def MiniTest.filter_backtrace(bt)
  bt
end
like image 162
Patrick Avatar answered Nov 08 '22 23:11

Patrick


Use this anywhere in you class to get full stack trace. I used it in my unit test case to debug my test class.

rescue => e

puts e.inspect

puts e.backtrace
like image 31
Milind Avatar answered Nov 09 '22 01:11

Milind