2011-05-15 86 views
1

我有給定一組學生和他們的等級的功能,使得分類:這是你如何測試功能以在Ruby中塊?

students = {"Good student":"A","Bad Student":"D","Average student":"C"} 
student_cat = ["Best","So-so","Below average"] 

我的功能是這樣的:現在我測試它像這樣

categorize(students,student_cat) do |s,g| 
    # s would be "Good student" and g would be "Best" 
    # s would be "Bad student" and g would be "Below average" 
    # s would be "Average student" and g would be "So-so" 
end 

categorize(students,student_cat) do |s,g| 
     assert g == "Best" if s == "Good student" 
     assert g == "Below average" if s == "Bad student" 
     assert g == "So-so" if s == "Average student" 
    end 

是否有另一種測試功能的方式以塊爲參數?這足夠好嗎?

+1

我不知道這是否是多數人的意見,但IMO塊,其返回的集合不應該屈服工作它的元素,這導致了必要的編碼(例如參見韋恩的答案)。因此通常:1)返回一個簡單陣列,或者2)如果期望長的輸出,返回一個枚舉(這是懶惰) – tokland 2011-05-15 14:09:00

回答

2

那將很好地工作。您可以測試多一點嚴格的,不過,如果你使用塊收集的結果,然後斷言整個結果:

results = [] 
categorize(students,student_cat) do |s,g| 
    results << [s, g] 
end 
assert results == [ 
    ["Good student", "Best"], 
    ["Bad Student", "Below average"], 
    ["Average student", "So-so"], 
] 

這樣的功能不能用正確的一起產生一些廢話結果並且不會被發現。

如果該功能可以以任意順序返回其結果,然後進行排序比較之前的結果:

assert results.sort == [ 
    ["Average student", "So-so"], 
    ["Bad Student", "Below average"], 
    ["Good student", "Best"], 
] 
+1

有的收錄,得到的數據的更好的方式:結果= enum_for(:分類,學生,貓)。 to_a。此外,它建議使用_assert_equal_,它提供了更有意義的錯誤消息。 – tokland 2011-05-15 13:52:32

+0

@tokland,'enum_for',很漂亮,我不知道。我同意'asesrt_equal',雖然提問沒有說他使用這些單元測試框架。 – 2011-05-15 14:06:40