我正在测试以下方法:
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类的实例变量。 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
使用流程Rspec测试代码,为什么即使输入正确也无法获得InvalidArgument
异常?
我实际上在CLI上使用了代码,它确实工作正常。
答案 0 :(得分: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