4

我想使用断言在 r​​ake 任务中引发错误。

the_index = items.index(some_item)
assert_not_nil the_index, "Lookup failed for the following item: " + some_item

我明白了undefined method assert_not_nil。我可以在我的 rake 任务中包含断言文件吗?如何?

这是最佳实践,还是有更好的方法?

在 Ruby 1.9.2 中工作。

4

3 回答 3

5

实际上,您可以在任何需要的地方使用断言。

require "minitest/unit"
include MiniTest::Assertions # all assertions are in this module
refute_nil @ivar, "An instance variable should not be nil here!"

但你为什么要这样做?而是自己提出有意义的例外。

于 2011-12-30T06:49:12.023 回答
3

有一个内置Array#fetch方法的行为类似于#[]但引发 IndexError 而不是在找不到元素时返回 nil 。(这同样适用于哈希。)如果我不希望集合排除某个元素,我总是使用第一个。

a = [:foo, :bar]
a.fetch(0)   #=> :foo
a[4]         #=> nil
a.fetch(4)   #=> IndexError: index 4 outside of array bounds: -2...2

对于其他情况,您自己会引发异常,例如 Bramha Ghosh 建议:

raise "I don't expect this to be nil!" if element.nil?

但是,您不应该经常这样做,除非您知道您的代码会在很远的地方失败,从而使调试变得痛苦。

于 2011-12-15T01:26:11.703 回答
1

您是否有特殊原因要使用断言?

为什么不

raise IndexError, "Lookup failed for the following item: #{some_item}" unless items.include? some_item
于 2011-12-15T00:40:00.970 回答