如何让我的代码通过 rspec 测试?

时间:2021-07-15 14:41:04

标签: ruby-on-rails ruby rspec

谁能阅读我的代码并告诉我为什么它一直未能通过 RSpec 测试?代码完美无缺,但测试在某些地方失败。我得到了预期的结果,但测试失败了。 我的代码用两个圆盘解决河内塔,也可以逆序移动(起始位置分别是1和2)。

工作代码:

def move(starting, goal)
  # your code here
  n = 2
  
  if starting == 1
    mid = 2
    toh(n, starting, mid, goal)
  else
    mid = 1
    toh(n, starting, mid, goal)
  end
end

def toh(n, starting, mid, goal)
  return puts "#{starting} -> #{goal}" if n == 1
  toh(n-1, starting, goal, mid)
  puts "#{starting} -> #{goal}"
  toh(n-1, mid, starting, goal)
  nil
end

puts move(1, 3)
# => 1->2 1->3 2->3

puts move(2, 3)
# => 2->1 2->3 1->3

RSpect 测试:

1 -> 2
1 -> 3
2 -> 3
F1 -> 2
1 -> 2
2 -> 2
F2 -> 1
2 -> 3
1 -> 3
F2 -> 1
2 -> 1
1 -> 1
F

Failures:

  1) UnitTests move_1_3
     Failure/Error: Unable to find (eval) to read failed line
     
     NoMethodError:
       undefined method `strip' for nil:NilClass
     # (eval):8:in `block (2 levels) in <top (required)>'

  2) UnitTests move_1_2
     Failure/Error: Unable to find (eval) to read failed line
     
     NoMethodError:
       undefined method `strip' for nil:NilClass
     # (eval):14:in `block (2 levels) in <top (required)>'

  3) UnitTests move_2_3
     Failure/Error: Unable to find (eval) to read failed line
     
     NoMethodError:
       undefined method `strip' for nil:NilClass
     # (eval):20:in `block (2 levels) in <top (required)>'

  4) UnitTests move_2_1
     Failure/Error: Unable to find (eval) to read failed line
     
     NoMethodError:
       undefined method `strip' for nil:NilClass
     # (eval):26:in `block (2 levels) in <top (required)>'

Finished in 0.06713 seconds (files took 0.99476 seconds to load)
4 examples, 4 failures

Failed examples:

rspec (eval)[1:1] # UnitTests move_1_3
rspec (eval)[1:2] # UnitTests move_1_2
rspec (eval)[1:3] # UnitTests move_2_3
rspec (eval)[1:4] # UnitTests move_2_1

这是原来的问题描述 挑战说明 河内塔 - 第 1 部分 在这个挑战中,您需要将 2 个磁盘从任何起始桩移动到任何目标桩。

您将获得两个数字(从 1 到 3)作为输入 - 起始标记和目标标记。编写一个函数来计算如何将 2 个圆盘从起始桩移动到目标桩。返回包含所有步骤的字符串。

输出格式:

添加要移动的定位点、箭头“->”和要移动到的定位点。例如,要从挂钩 1 移动到挂钩 3,请打印“1->3”。

示例 移动(1, 3)

=> 1->2 1->3 2->3

移动(2, 3)

=> 2->1 2->3 1->3

0 个答案:

没有答案