单元测试Ruby时出错

时间:2016-05-18 18:53:32

标签: ruby unit-testing

如果三元组的总和等于给定数字

,则以下代码返回true
class triplet
def three_sum_fast(ary, sum)
  ary.sort!

  (0..ary.length - 3).each do |i|
    front = ary[i]
    start_index = i + 1
    back_index = ary.length - 1

    while(start_index < back_index) do
      start = ary[start_index]
      back = ary[back_index]

      if (front + start + back) > 0
        back_index -= 1
      else
        start_index += 1
      end

       if front + start + back == sum
          return true
          break
      end

    end

  end
  false
end

end

以下代码是测试文件

require  "test/unit"
require  "triplet.rb"

class Test < Test::Unit::TestCase
    def test_trip
        num=triplet.new
        num.three_sum_fast({1,3,4,5,6,7},14)
        assert_equal (expected,true)
    end
end

发现的错误是:

syntax error, unexpected ',', expecting =>
    num.three_sum_fast({1,3,4,5,6,7},14)
syntax error, unexpected ',', expecting ')'
    assert_equal (expected,true)

1 个答案:

答案 0 :(得分:1)

班级名称

类名是常量,因此必须以大写字母开头:

class Triplet
  # ...
end

在你的测试中:

num = Triplet.new

数组文字

通过[]创建数组,而通过{}创建哈希,即

num.three_sum_fast([1, 3, 4, 5, 6, 7], 14)

方法调用

下一行有一个错误的空间:

assert_equal (expected,true)
#           ^
#           that one is wrong

必须是:

assert_equal(expected, true)
#                     ^
#                     that one is okay

未定义的变量

即使删除了错误的空间,该行也不起作用,因为expected是未定义的变量。在使用之前,您必须分配

expected = num.three_sum_fast([1, 3, 4, 5, 6, 7], 14)
assert_equal(expected, true)

这样可行,但expected用词不当。 true预期的值,而方法的结果是实际值。所以它应该是:

actual = num.three_sum_fast([1, 3, 4, 5, 6, 7], 14)
assert_equal(true, actual)

或简单地说:

assert_equal(true, num.three_sum_fast([1, 3, 4, 5, 6, 7], 14))