我遇到的问题是,当随机数低于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
答案 0 :(得分: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
答案 1 :(得分:2)
使用rand
生成一系列数字,以涵盖特定情况,以便覆盖角落案例。
我会使用let
来做这样的天气范围的懒惰实例化:
let(:weather_above_20) { rand(20..100) }
let(:weather_below_20) { rand(0..20) }
然后我会在我的测试中使用weather_above_20
和weather_below_20
变量。最好隔离测试条件。
关于懒惰实例化的更多信息: https://www.relishapp.com/rspec/rspec-core/docs/helper-methods/let-and-let
答案 2 :(得分:0)
allow_any_instance_of(Object).to receive(:rand).and_return(5)