4

我有一个问题,这些测试只有在随机数低于 20 时才能通过,我如何在测试中解决这个问题?

我的测试:

it 'a plane cannot take off when there is a storm brewing' do
    airport = Airport.new [plane]
    expect(lambda { airport.plane_take_off(plane) }).to raise_error(RuntimeError) 
end

it 'a plane cannot land in the middle of a storm' do
    airport = Airport.new []
    expect(lambda { airport.plane_land(plane) }).to raise_error(RuntimeError) 
end

我的代码摘录:

def weather_rand
  rand(100)
end

def plane_land plane
  raise "Too Stormy!" if weather_ran <= 20
  permission_to_land plane
end

def permission_to_land plane
  raise "Airport is full" if full?
  @planes << plane
  plane.land!
end

def plane_take_off plane
  raise "Too Stormy!" if weather_ran <= 20
  permission_to_take_off plane
end

def permission_to_take_off plane
  plane_taking_off = @planes.delete_if {|taking_off| taking_off == plane }
  plane.take_off!
end
4

3 回答 3

5

您需要存根该weather_rand方法以返回一个已知值以匹配您要测试的内容。

https://www.relishapp.com/rspec/rspec-mocks/v/2-14/docs/method-stubs

例如:

it 'a plane cannot take off when there is a storm brewing' do
    airport = Airport.new [plane]
    airport.stub(:weather_rand).and_return(5)
    expect(lambda { airport.plane_take_off(plane) }).to raise_error(RuntimeError) 
end
于 2013-10-18T13:58:17.080 回答
3

用于rand生成将涵盖特定情况的一系列数字,以便您涵盖极端情况。我会let像这样对天气范围进行惰性实例化:

let(:weather_above_20) { rand(20..100) }
let(:weather_below_20) { rand(0..20) }

然后我会在我的测试中使用weather_above_20andweather_below_20变量。最好始终隔离测试条件。

关于惰性实例化的更多信息: https ://www.relishapp.com/rspec/rspec-core/docs/helper-methods/let-and-let

于 2013-10-19T02:59:14.503 回答
0
allow_any_instance_of(Object).to receive(:rand).and_return(5)
于 2019-03-20T00:33:48.007 回答