2016-11-13 34 views
2

所以我有一個Weather類,它應該返回隨機結果,並且我想使用stub來測試它。我在這http://www.martinfowler.com/articles/mocksArentStubs.html 閱讀馬丁花的文章,我覺得這將是最簡單的解決方案。但很難找到任何語法的例子。你能給我一個測試的例子嗎?這是我功課的一部分。在rspec中使用stub來測試rand的輸出

class Weather 

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

    def chance 
    rand 
    end 

end 

回答

2

根據你的例子,你想測試chance而不是執行的行爲。

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 
+0

很酷。很好,很簡單 – Agata