RSpec: How to stub a random variable (make the weather as you need it to be)

Will it rain, or not? How to stub a method in Spec tests.

In our last challenge there was an airport that gave or declined landing permission for planes based on the weather. There was no real weather forecast, I just generated a random weather:

def generate_weather
[:sunny, :sunny, :sunny, :stormy].shuffle.first
end

The Ruby-method .shuffle randomly mixes the values within the array and .first than takes the first value out.

RSpec test: force the function return a specific value

I implemented an if-statement in my landing- and take-off-procedures. So that a plane could only land if weather was sunny. But the if-statement made the tests randomly fail I had written to check those methods. Very annoying. Red type all over my terminal.

Luckily RSpec gives you the possibility to stub methods. I didn’t quite understand how that works. But now that I have understood I try to explain it out of a beginner’s perspective:

If I want my generate_weather method (above) for testing-purposes to return always :stormy, I set the following line in the beginning of my RSpec-Test:

expect(plane).to receive(:generate_weather).and_return(:stormy)

Translation: If the method generate_weather is sent to the object plane, it will return :stormy – no matter what generate_weather actually generated.