Test::Unit Rails - How to assert one number is greater than another one?
Asked Answered
B

3

52

I am writing my first unit tests with Test::Unit and I have reached a point where I need to compare two numbers. Much to my surprise, I have discovered that none of the following were available:

assert_greater_than
assert_lesser_than
assert_greater_or_equal_than
assert_lesser_or_equal_than

Is this normal? How should I do it then?

Thanks

Bushed answered 28/4, 2011 at 13:54 Comment(0)
H
81

Rather than provide a bunch of different assertions as you suggest, Test::Unit provides the method assert_operator, used like this:

assert_operator x, :>, y
assert_operator x, :>=, y
etc. 
Hyonhyoscine answered 28/4, 2011 at 13:59 Comment(0)
K
16

How about this simple thing,

assert x>y
Kilohertz answered 28/4, 2011 at 13:56 Comment(3)
Assert() can almost always be used to apply a given test, but it should be a last resort, because it gives much less meaningful results in the event of failure. In this case, a better approach is to use assert_operator.Hyonhyoscine
I am getting an undefined method `assert_true'. Is it deprecated?Bushed
The actual assertion to use with a boolean is just assert, not assert_true.Hyonhyoscine
M
8

Here are some functions you can put in test/test_helper.rb

  def assert_gt(a, b)
    assert_operator a, :>, b
  end
  
  def assert_gte(a, b)
    assert_operator a, :>=, b
  end

  def assert_lt(a, b)
    assert_operator a, :<, b
  end

  def assert_lte(a, b)
    assert_operator a, :<=, b
  end

Then call like so:

assert_gt 6, 3
assert_gte 5, 5
assert_lt 4, 5
assert_lte 5, 5
Masuria answered 28/9, 2017 at 19:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.