Freddy
Freddy

Reputation: 1229

Making a method return a specific value (that would otherwise be random) in Rspec

I'm trying to write an rspec test that would assume a method will return a specific value when it would normally return a random number between 1 and 10.

Here is the code in my lib directory:

  def take_off(plane)
    fail "Bad weather today. Cannot take off." if stormy_weather? > 8
    plane.take_off_plane
    planes.delete(plane)
  end

  def stormy_weather?
    rand(10)
  end

And here is my test in Rspec:

it 'raises an error when weather is stormy' do
  plane = double(:plane)
  stormy_weather = 9
  allow(plane).to receive(:take_off_plane)
  expect{ subject.take_off(plane) }.to raise_error("Bad weather today. Cannot take off.")
end

Thank you in advance to anyone who helps!

Upvotes: 0

Views: 65

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

You can specify the returned value with and_return:

allow(subject).to receive(:stormy_weather?).and_return(9)

Upvotes: 1

Related Questions