Agata Agata - 20 days ago 6
Ruby Question

Using stub in rspec to test output of a rand

so I have a class Weather, that should return random results, and I'd like to test it using stub. I read the article of Martin Flower on this http://www.martinfowler.com/articles/mocksArentStubs.html
and I feel it would be the easiest solution. But it's difficult to find any examples of syntax. Could you give me an example of a test. This is part of my homework.

class Weather

def conditions
return :good if chance > 0.3
:stormy
end

def chance
rand
end

end

Answer

Based on your example, you want to test the behavior of chance not the implementation.

describe Weather do
  it 'returns good' do
    weather = Weather.new
    allow(weather).to receive(:chance).and_return(0.8)
    expect(weather.conditions).to eq :good
  end
end
Comments