JamesJY
JamesJY

Reputation: 135

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?

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

Upvotes: 4

Views: 4191

Answers (3)

Jerome Dalbert
Jerome Dalbert

Reputation: 10405

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

Upvotes: 0

Backnol
Backnol

Reputation: 101

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

Upvotes: 3

sevenseacat
sevenseacat

Reputation: 25029

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

Upvotes: 5

Related Questions