如何在我的rspec测试中考虑随机数?

Jam*_*sJY 2 ruby rspec ruby-on-rails ruby-on-rails-3

我有一个问题,即当随机数低于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
Run Code Online (Sandbox Code Playgroud)

我的代码摘录:

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
Run Code Online (Sandbox Code Playgroud)

sev*_*cat 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
Run Code Online (Sandbox Code Playgroud)