gpt4 book ai didi

ruby - 如何在 rspec 中测试 .sample 方法?

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:13 25 4
gpt4 key购买 nike

我正在用 rspec 编写测试:

it "should choose a sign at random" do
game.choose_sign
expect(game.choose_sign).to eq "rock"
end

ruby 代码:

def choose_sign
["rock","paper","scissor"].sample
end

The code works but the test only passes when one of the values has been selected that matches whatever I put in the rspec test i.e. eq "rock"

如何让它每次都通过?这对于将来测试随机返回值时的引用非常有用。

最佳答案

您可以测试预期的集合包括您的方法的结果:

it "chooses a random sign" do
expect(["rock","paper","scissor"]).to include(game.choose_sign)
end

关于ruby - 如何在 rspec 中测试 .sample 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26206237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com