Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend Ruby Test::Unit assertions to include assert_false?

Apparently there is no assert_false in Test::Unit. How would you add it by extending assertions and adding the file config/initializers/assertions_helper.rb?

Is this the best way to do it? I don't want to modify test/unit/assertions.rb.

By the way, I don't think it is redundant. I was using assert_equal false, something_to_evaluate. The problem with this approach is that it is easy to accidentally use assert false, something_to_evaluate. This will always fail, doesn't throw an error or warning, and invites bugs into the tests.

like image 242
B Seven Avatar asked Nov 24 '11 17:11

B Seven


2 Answers

If you're using MiniTest (replaced Test::Unit in Ruby 1.9+), then you can use the refute method, which is the inverse of assert.

like image 199
Jake Bellacera Avatar answered Nov 04 '22 19:11

Jake Bellacera


Personally I find the name assert_false better than refute because it's consistent with all the other assertions, and it's also usually more aligned with the semantics (similar to using if !condition instead of unless).

If you feel the same way and want assert_false, add it in test/test_helper.rb:

class ActiveSupport::TestCase

  ...

  def assert_false(test, message="Expected: false. Actual: #{test}.")
    assert_equal false, test, message
  end

end

EDIT: Note that assert !test (suggested elsewhere) wouldn't work if test is nil (!nil is true, and we probably want assert_false(nil) to fail). So this is a direct comparison to false.

like image 29
mahemoff Avatar answered Nov 04 '22 20:11

mahemoff