开发者

Is this how you test functions taking a block in Ruby?

开发者 https://www.devze.com 2023-03-05 20:07 出处:网络
I have a function which given a set of students and their grades, makes a categorization: students = {\"Good student\":\"A\",\"Bad Student\":\"D\",\"Average student\":\"C\"}

I have a function which given a set of students and their grades, makes a categorization:

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

And my function works like this:

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

Right now I'm testing it like this:

  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

Is there another way of testing functions take blocks as paramet开发者_如何学Pythoners? Is this a good enough way?


That'll work fine. You can make the test a little more strict, though, if you use the block to collect the results, and then assert the entire result:

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"],
]

That way the function can't yield some nonsense along with the proper results and have it go undetected.

If the function may return its results in any order, then sort results before comparing it:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号