RSpec提出异常 - 预期的异常,但没有提出任何回复?

时间:2016-05-28 21:56:21

标签: ruby exception rspec

我正在进行编码挑战,并且正在尝试进行一次RSpec测试,但是我不确定为什么我的代码没有通过。运行RSpec后我得到的错误是:

1)如果已经着陆,则平面#land会引发错误      失败/错误:期待{plane.land} .to raise_error'飞机无法降落,因为它已经在地面上'        预期的例外情况是“飞机不能降落,因为它已经在地面上”,但没有提出任何问题      #。/ spec / plane_spec.rb:22:在'

中的块(3级)

RSpec测试代码是:

describe Plane do

  let(:plane) { Plane.new }

describe '#land' do
    it 'raises an error if already landed' do
      plane.land
      expect { plane.land }.to raise_error 'Plane can not land as it is already on the ground'
    end
  end

我的主要代码是:

class Plane

  def initialize
    @in_air = true
  end

  def land
    fail "Plane can not land as it is already on the ground" if already_landed?
    @in_air = false
  end
end

我尝试用后挡板替换Plane.new并尝试使用raise代替fail并且我已经进行了双重检查,但我不明白为什么它不起作用。

非常感谢

1 个答案:

答案 0 :(得分:0)

您尚未定义already_landed?方法。这意味着调用already_landed?将始终引发NoMethodError: undefined method 'already_landed?'异常,但绝不会引发预期的Plane can not land...异常。因此,你的期望不会过去。

只需将already_landed?方法添加到您的模型中:

class Plane
  def initialize
    @in_air = true
  end

  def land
    fail "Plane can not land as it is already on the ground" if already_landed?
    @in_air = false
  end

  def already_landed?
    !@in_air
  end
end

顺便说一句:新创建的飞机已经in_air了吗?我希望in_air在初始化时为false,并且您需要先start。我会改变这种行为:

class Plane
  attr_accessor :flying

  def fly
    # no exception here, I assume it is save to continue flying, when already in air
    self.flying = true
  end

  def land
    fail 'Plane can not land as it is already on the ground' if landed
    self.flying = false
  end

  def landed
    !flying
  end
end

plane = Plane.new
plane.land
#=> RuntimeError: Plane can not land as it is already on the ground