在使用块之前导致失败的Rspec测试

时间:2017-03-20 21:49:30

标签: ruby rspec

我在使用Rspec中的before块时遇到了一些问题。在下面的代码中,我无法删除allow(plane).to receive(:land_plane)行。在第二块代码中,我遇到了同样的问题,但是allow(plane).to receive(:take_off_plane)。非常感谢任何帮助!

describe '#land' do
    context 'when not stormy' do
      before :each do
        allow(airport.weather).to receive(:stormy_weather?).and_return(false)
        allow(plane).to receive(:land_plane)
      end
      it 'should tell the plane to land' do
        plane = double(:plane, airborne: true)
        allow(plane).to receive(:land_plane) # can't put this into before block?
        expect(airport).to receive(:land)
        airport.land(plane)
      end

      it 'should have plane in the Airport' do
        plane = double(:plane, airborne: true)
        allow(plane).to receive(:land_plane)
        airport.land(plane)
        expect(airport.planes_in_airport).to include plane
      end

      it 'should raise error when trying to land a landed plane' do
        plane = double(:plane, airborne: false)
        message = "This plane is already landed."
        expect{ airport.land(plane) }.to raise_error message
      end

      context 'when full' do
        it 'should raise an error' do
          plane = double(:plane, airborne: true)
          allow(plane).to receive(:land_plane)
          airport.capacity.times {airport.land(plane)}
          message = "Sorry. Airport full. Go away."
          expect{airport.land(plane)}.to raise_error message
        end
      end
    end

-

describe '#take_off' do
    context 'when not stormy'
    before do
      allow(airport.weather).to receive(:stormy_weather?).and_return(false)
      allow(plane).to receive(:take_off_plane)
    end
    it 'should remove plane from Airport' do
      plane = double(:plane, airborne: false)
      allow(plane).to receive(:take_off_plane) # can't delete this
      airport.planes_in_airport.push(plane)
      airport.take_off(plane)
      expect(airport.planes_in_airport).not_to include(plane)
    end
  end

1 个答案:

答案 0 :(得分:0)

我找到了答案。

这里面临的挑战是我在预期中错误地创造了新的双打。例如:

plane = double(:plane, airborne: true)

在这里,我不应该使用allow(plane).to receive(:land_plane)行。或者,就此而言,那里也有before :each do allow(plane).to receive(:airborne).and_return(true) allow(plane).to receive(:land_plane) allow(airport.weather).to receive(:stormy_weather?).and_return(false) end 。我应该在前一块

中都有

我应该让我的前一块看起来像这样:

String

这使我无需在每个期望中创建那些奇怪的双打。这也意味着飞机的空中状态是预先定义的。这在我允许平面double接收land_plane方法之前发生。我之前以错误的方式执行此操作意味着我在告诉它接受land_plane方法后创建了一个double,导致意外的消息异常。

感谢您查看并告诉我您是否还有其他要点!