【发布时间】:2016-07-05 04:31:08
【问题描述】:
我一直在编写一系列比较字符串、数组等的小型 Ruby 程序。我目前正在学习如何为我的方法编写小型单元测试。我已经能够编写在字符串上执行函数的简单测试,但是当涉及到更困难的测试时,比如在数组上执行函数的测试,我不知道。如果有人可以帮助我解决当前的问题,我将不胜感激。
假设我的文件夹中有三个文件:program.rb、plant_methods.rb 和 tc_plant_methods.rb
这是 plant_methods.rb 中的内容。它包含一个具有两个可用方法的类。 plant_sort 方法循环遍历数组,并根据数组中的第一项对它们进行字母排序。
class Plant_Methods
def initialize
end
def self.plant_sort(array)
array.sort! { |sub_array1, sub_array2|
sub_array1[0] <=> sub_array2[0] }
end
end
这是program.rb中的代码
require_relative 'plant_methods'
plant_array = [['Rose', 'Lily', 'Daisy'], ['Willow', 'Oak', 'Palm'], ['Corn', 'Cabbage', 'Potato']]
Plant_Methods.plant_sort(plant_array)
print plant_array
这是运行 program.rb 时的输出。现在,每个子数组都按照第一个元素按字母顺序排列:
[["Corn", "Cabbage", "Potato"], ["Rose", "Lily", "Daisy"], ["Willow", "Oak", "Palm"]]
现在,我的问题是:如何为此编写单元测试?这是我的 tc_plant_methods.rb 文件中当前的内容:
require_relative "plant_methods"
require_relative "program"
require "test/unit"
class Test_Plant_Methods < Test::Unit::TestCase
def test_plant_sort
assert_equal("[["Gingko", "Beech"], ["Rice", "Wheat"], ["Violet", "Sunflower"]]", Plant_Methods.new([["Violet", "Sunflower"], ["Gingko", "Beech"], ["Rice", "Wheat"]]).plant_sort([["Violet", "Sunflower"], ["Gingko", "Beech"], ["Rice", "Wheat"]]))
end
end
我在尝试运行单元测试时不断出错。我在这里做错了什么,任何人都可以识别吗? 这是我尝试运行测试时出现的第一个错误:
tc_plant_methods.rb:8: syntax error, unexpected tCONSTANT, expecting ')'
【问题讨论】:
标签: arrays ruby unit-testing sorting