2011-12-15 53 views
3

我想使用一個斷言來引發rake任務中的錯誤。在Ruby中使用斷言的最佳實踐是什麼,但不是作爲單元測試的一部分?

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。

+1

單元測試和異常處理是兩個非常不同的事情。 – 2011-12-15 03:15:13

回答

3

有一個內置的Array#fetch方法,其作用類似於#[]但引發IndexError,而不是在未找到該元素,返回nil。 (這同樣適用於Hash。)如果我不希望集合排除元素,則始終使用第一個。

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

而對於其他情況自己拋出異常喜歡Bramha戈什表明:

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

然而,你不應該經常這樣做,只有當你知道你的代碼將失敗遠製作調試痛苦。

1

是否有一個特殊原因需要使用斷言?

爲什麼不

raise IndexError, "Lookup failed for the following item: #{some_item}" unless items.include? some_item 
+0

使它看起來像單元測試。它使它更具可讀性。 – 2011-12-26 19:00:19

5

你可以在任何你想要的地方使用斷言。

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

但是,你爲什麼要這樣做?而是自己提出有意義的例外。

相關問題