How to know your ruby Test::Unit test result

If a test passes, you usually don’t want to know any more – nothing to see here, move along. But, if a test fails or errors, you become far more interested. But… how to know if a test failed or not? If you could tell, you could do useful things like taking screenshots, writing stack traces to a file, etc. So it’d be useful to know the result.

Using ruby’s Test::Unit, it’s easy. Since test cases inherit from Test::Unit::TestCase, and since Test::Unit::TestCase contains an instance variable called @test_passed – a boolean, you can access the result  of your test with no problem. So the following is possible:


class MyTests < Test::Unit::TestCase
  def setup
    #do nothing
  end
  def teardown
    if @test_passed then
      puts "Yay! The test passed!"
    else
      puts "Oh no! The test went bad!"
    end
  end
  def test_that_passes
    assert(true)
  end
  def test_that_fails
    assert(false)
  end
end

See the code in the teardown? It’s doing stuff based on the test result. I’m sure you can come up with a better use for this than printing silly strings…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>