使用assert_in_delta
,例如:
assert_in_delta -9.04, elts[2].change, 0.01
还请参见:Test::Unit::Assertions#assert_in_delta:https ://www.rubydoc.info/github/test-unit/test-unit/Test%2FUnit%2FAssertions:assert_in_delta
例如,这通过:
assert_in_delta 0.33, 1.0/3, 0.01
最初的测试失败可能是由比较或类似float
的BigDecimal
东西引起的。显然,Ruby 需要这种比较中的类来匹配。这是一个重现类似行为的简单示例:
bar = -9.04 # Float
baz = BigDecimal.new("-0.904e1") # BigDecimal (not Float)
puts bar == baz # false
puts bar == baz.round(2) # false (even after rounding!)
puts bar == baz.to_f # true (converted to Float)
puts bar == baz.to_f.round(2) # true (same, plus rounded)