2013-10-18 3 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

관련 문제