2013-10-18 28 views
1

我有一個問題,只有當隨機數低於20時,這些測試纔會通過,我如何在測試中解釋這個問題?如何在我的rspec測試中考慮隨機數?

我的測試:

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 

回答

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 
+0

或提供的隨機數發生器,它最終是更靈活反正的實現。 –

1

使用rand生成一個範圍,因此覆蓋的角落的情況下,將覆蓋特定情況下的數字。 我會用let做天氣範圍的延遲實例是這樣的:

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

然後我會使用weather_above_20weather_below_20變量在我的測試。最好隔離測試條件。

更多關於有點懶實例: https://www.relishapp.com/rspec/rspec-core/docs/helper-methods/let-and-let