【问题标题】:Testing in Ruby - how to write a test that compares sub-arrays in an array?Ruby 中的测试 - 如何编写一个比较数组中子数组的测试?
【发布时间】:2016-07-05 04:31:08
【问题描述】:

我一直在编写一系列比较字符串、数组等的小型 Rub​​y 程序。我目前正在学习如何为我的方法编写小型单元测试。我已经能够编写在字符串上执行函数的简单测试,但是当涉及到更困难的测试时,比如在数组上执行函数的测试,我不知道。如果有人可以帮助我解决当前的问题,我将不胜感激。

假设我的文件夹中有三个文件: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


    【解决方案1】:

    错误是由于表达式中的双引号使用不正确,

    "[["Gingko", "Beech"], ["Rice", "Wheat"], ["Violet", "Sunflower"]]"
    

    这里,“[[”标记了字符串[[

    的开始和结束

    为什么不断言数组的相等性而不是断言字符串的相等性?

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

    【讨论】:

      猜你喜欢
      • 2010-11-30
      • 1970-01-01
      • 2010-12-04
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多