如何扩展 Ruby Test::Unit 断言以包含assert_false?
显然 Test::Unit 中没有 assert_false
。如何通过扩展断言并添加文件 config/initializers/assertions_helper.rb 来添加它?
这是最好的方法吗?我不想修改 test/unit/assertions.rb
。
顺便说一句,我不认为这是多余的。我使用的是 assert_equal false, Something_to_evaluate
。这种方法的问题是很容易意外使用 assert false, Something_to_evaluate
。这总是会失败,不会抛出错误或警告,并且会在测试中引入错误。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您使用 MiniTest(在 Ruby 1.9+ 中被替换为 Test::Unit),那么您可以使用
refute
方法,该方法与assert
相反。If you're using MiniTest (replaced Test::Unit in Ruby 1.9+), then you can use the
refute
method, which is the inverse ofassert
.就我个人而言,我发现名称
assert_false
比refute
更好,因为它与所有其他断言一致,而且通常也更符合语义(类似于使用if !条件
而不是除非
)。如果您有同样的感觉并且想要
assert_false
,请将其添加到test/test_helper.rb
中:编辑:请注意
assert !test
(在其他地方建议) ) 如果test
为 nil 则不起作用(!nil 为 true,我们可能希望assert_false(nil)
失败)。所以这是与false
的直接比较。Personally I find the name
assert_false
better thanrefute
because it's consistent with all the other assertions, and it's also usually more aligned with the semantics (similar to usingif !condition
instead ofunless
).If you feel the same way and want
assert_false
, add it intest/test_helper.rb
:EDIT: Note that
assert !test
(suggested elsewhere) wouldn't work iftest
is nil (!nil is true, and we probably wantassert_false(nil)
to fail). So this is a direct comparison tofalse
.Rails 4 有
assert_not
可以满足您的需求。Rails 4 has
assert_not
which does what you want.只需在您声明的内容前面添加一个感叹号即可:
Just add a bang in front of what you are asserting:
检查 false 值的唯一正确方法是使用
assert_equal(val, false)
,因为诸如refute(val)
之类的方法,当 val = nil 时,assert_not(val)
或assert(!val)
都返回true
,而不是false
> 正如你所期望的那样。The only true way to check for a false value is to use
assert_equal(val, false)
, since methods such asrefute(val)
,assert_not(val)
orassert(!val)
all returntrue
in case when val = nil, and notfalse
as you would expect.