Add assert_false to Ruby’s Test::Unit

For the past few months, I’ve been using NUnit. A few days ago I started using ruby’s Test::Unit – the only thing I miss from nunit is Assert.IsFalse(). So here’s something that will do the job… add the following code somewhere early on in the sequence:


module Test::Unit::Assertions
  def assert_false(object, message="")
    assert_equal(false, object, message)
  end
end

Here’s some code you can stick in a file that will prove the above method works:


require "test/unit"

module Test::Unit::Assertions
  def assert_false(object, message="")
    assert_equal(false, object, message)
  end
end

puts Test::Unit::TestCase.method_defined?(:assert_false)

class MyTests < Test::Unit::TestCase
  def test_this_one_fails
    assert_false(false)
    assert_false(true)
  end
  def test_this_one_passes
    assert_false(false)
  end
  def test_this_one_passes_too
    assert(true)
  end
end

=========UPDATE=========

After emailing Nathaniel Talbott (the author of Test::Unit), it turns out that he’s no longer the maintainer. That job has passed on to Ryan Davis, and he’s writing a replacement for Test::Unit. So I guess assert_false will never make it in. If you want assert_false, use the monkeypatch above!

Stop Ruby’s Test::Unit suite files running all your tests

Ruby’s Test::Unit has a very cool feature… you can quickly build test suites by having a file which ‘requires’ all the test case files. Running the file will find all the test cases, and run them all. Very useful. Unless you want to have access to all the test cases, but don’t want to run them – eg: when you want to count how many test cases you have of each type. To do that, make sure the top two lines of your test suite file are:


require "test/unit"
Test::Unit.run=true

Yeah, the =true bit is counter-intuitive.
Test::Unit.run=true … and your tests won’t run
Test::Unit.run=false … and your tests will run
Weird, huh?