这是你如何测试在Ruby中使用块的函数?

时间:2011-05-15 12:50:19

标签: ruby unit-testing

我有一个功能,给一组学生和他们的成绩,进行分类:

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 个答案:

答案 0 :(得分: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"],
]