0

我正在测试以下方法:

def place(arguments)
  begin 
    argument = String(arguments).split(",")
    x_coordinate = argument[0].to_i
    y_coordinate = argument[1].to_i
    direction = argument[2].downcase.to_sym
    puts "Not placed. Please provide valid arguments" unless @robot.place(x_coordinate, y_coordinate, direction)
  rescue
    raise InvalidArgument
  end
end

InvalidArgument = Class.new(Exception)

使用此代码进行测试:

describe '#process' do
  it 'Process the command and place the robot' do
    expect( command.process("place 3,4,north") ).to eq(nil)
  end
end

@robot是 Robot 类的实例变量。机器人类继承自Actions类。Robot 类没有place方法,但 Actions 类如下所示:

require 'active_model'
require_relative 'board'
require_relative 'direction'
require_relative 'report'

# Contains all base action methods to support robot and other objects in future
class Actions
  include ActiveModel::Validations

  attr_accessor :x_coordinate, :y_coordinate, :direction, :placed

  validates :x_coordinate, presence: true, numericality: { only_integer: true }
  validates :y_coordinate, presence: true, numericality: { only_integer: true }

  def initialize(landscape)
    @landscape = landscape
    @map = Direction::Map.new
    self
  end

  def place(x_coordinate, y_coordinate, direction = :north)
    if within_range(x_coordinate, y_coordinate, direction)
      @placed = true
      report
    end
  end

  def within_range(x_coordinate, y_coordinate, direction)
    self.x_coordinate, self.y_coordinate, self.direction = x_coordinate, y_coordinate, direction if
    x_coordinate.between?(@landscape.left_limit, @landscape.right_limit) && 
      y_coordinate.between?(@landscape.bottom_limit, @landscape.top_limit) &&
      @map.directions.grep(direction).present?
  end

  def left
    self.direction = @map.left(self.direction)
    report
  end

  def right
    self.direction = @map.right(self.direction)
    report
  end

  def move_forward(unit = 1)
    x_coord, y_coord, direct = self.x_coordinate, self.y_coordinate, self.direction

    case direct
    when Direction::SOUTH
      place(x_coord, y_coord - unit, direct)
    when Direction::EAST
      place(x_coord + unit, y_coord, direct)
    when Direction::NORTH
      place(x_coord, y_coord + unit, direct)
    when Direction::WEST
      place(x_coord - unit, y_coord, direct)
    end
  end

  def report_current_position
    "#{@report.join(', ')}" if @report
  end

  def report
    @report = Report.new(self.x_coordinate, self.y_coordinate, self.direction).to_a 
  end

end

InvalidArgument使用流程 Rspec 测试代码,即使输入正确,为什么我也会收到异常?

我实际上在 CLI 上使用了代码,它肯定工作正常。

4

1 回答 1

0

使用rescue而不告诉 Ruby 你想拯救哪些异常是一个坏主意。

以下代码将捕获任何StandardError 异常,甚至调用未定义的方法,例如:

def foo
  # do stuff
rescue
  puts "will go here for any StandardError exceptions"
end

您应该使用rescue传递要救援的异常:

def foo
  # do stuff
rescue SomeException
  puts "will go here for all exceptions of type SomeException"
end
于 2013-08-28T07:40:40.417 回答