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?
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.
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.
I would use let
to do the lazy instantiation of the weather ranges like this:
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. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With