简体   繁体   English

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

[英]How do I take into account the random number in my rspec tests?

I am having a problem that these tests only pass when the random number is below 20, how do I account for this in my tests? 我有一个问题,这些测试仅在随机数小于20时通过,我如何在测试中说明这一点?

My tests: 我的测试:

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

My code excerpt: 我的代码摘录:

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

You would need to stub the weather_rand method to return a known value to match what you are trying to test. 您需要存根weather_rand方法以返回已知值以匹配您要测试的内容。

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

For example: 例如:

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

Use rand to generate a range of numbers that will cover a specific case so you cover the corner cases. 使用rand生成一系列覆盖特定情况的数字,以便覆盖角落情况。 I would use let to do the lazy instantiation of the weather ranges like this: 我会用let来做这样的天气范围的懒惰实例化:

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

Then I would use the weather_above_20 and weather_below_20 variables in my tests. 然后我会在我的测试中使用weather_above_20weather_below_20变量。 It is always best to isolate test conditions. 最好隔离测试条件。

Little more about the lazy instantiation: https://www.relishapp.com/rspec/rspec-core/docs/helper-methods/let-and-let 关于延迟实例的更多信息: https : //www.relishapp.com/rspec/rspec-core/docs/helper-methods/let-and-let

allow_any_instance_of(Object).to receive(:rand).and_return(5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM