这就是在 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
是否有另一种测试函数以块作为参数的方法?这是一个足够好的方法吗?
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 parameters? Is this a good enough way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这样就可以了。不过,如果您使用块来收集结果,然后断言整个结果,则可以使测试更加严格一些:
这样该函数就不会在正确的结果中产生一些无意义的内容,并且不会被发现。
如果函数可以按任何顺序返回其结果,则在比较之前对结果进行排序:
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:
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: