How to extend Ruby Test::Unit assertions to include assert_false?
Asked Answered
B

5

6

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.

Bartizan answered 24/11, 2011 at 17:33 Comment(1)
natontesting.com/2009/07/21/add-assert_false-to-rubys-testunit, the work link is a hyperlink but see the same above.Agate
P
10

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.

Presentation answered 27/2, 2013 at 1:31 Comment(0)
F
5

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.

Flummox answered 24/1, 2014 at 18:7 Comment(0)
E
4

Rails 4 has assert_not which does what you want.

test "requires valid url" do
  @mymodel.url = "bogus!"
  assert_not @mymodel.valid?
end
Eadie answered 8/3, 2014 at 22:21 Comment(0)
P
3

Just add a bang in front of what you are asserting:

assert !(something_false)
Peach answered 7/9, 2012 at 18:18 Comment(0)
D
0

The only true way to check for a false value is to use assert_equal(val, false), since methods such as refute(val), assert_not(val) or assert(!val) all return true in case when val = nil, and not false as you would expect.

Depend answered 29/4 at 11:34 Comment(1)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewMulkey

© 2022 - 2024 — McMap. All rights reserved.