How to get stack trace from a Test::Unit::TestCase
Asked Answered
R

2

13

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?

Rigger answered 19/2, 2012 at 2:23 Comment(2)
Are you running your test with rake?Isolative
Was this in Ruby 1.8, Ruby 1.9, or both?Millais
G
14

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
Garganey answered 19/2, 2012 at 5:11 Comment(0)
H
1

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
Harald answered 26/6, 2012 at 8:11 Comment(1)
Your solution is OK, but the problem is that it would negate the need for existence of Test::Unit - you suggest to manually trace all exceptions. The question was - how to fix Test::Unit to be useful again.Arietta

© 2022 - 2024 — McMap. All rights reserved.