I am writing a test in rspec:
我在rspec写一个测试:
it "should choose a sign at random" do
game.choose_sign
expect(game.choose_sign).to eq "rock"
end
ruby code:
红宝石代码:
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"
代码有效但测试只在选择了其中一个值与我在rspec测试中输入的值相匹配时才通过,即eq“rock”
How do I make it pass every time? This would be really useful to know for future reference when testing for random return values.
我怎样每次都通过?在测试随机返回值时,这对于了解将来的参考非常有用。
2 个解决方案
#1
2
You can test that expected collection include result of your method:
您可以测试预期的集合包括方法的结果:
it "chooses a random sign" do
expect(["rock","paper","scissor"]).to include(game.choose_sign)
end
#2
1
I would suggest to test the logic rather than particular value being return. You can test for rerun value not being nil or not being empty. Sample method will return random value from array which will make harder for you to pass test everytime. Hope it helps.
我建议测试逻辑而不是返回特定值。您可以测试重新运行值不是nil或不为空。 Sample方法将从数组中返回随机值,这将使您每次都难以通过测试。希望能帮助到你。
#1
2
You can test that expected collection include result of your method:
您可以测试预期的集合包括方法的结果:
it "chooses a random sign" do
expect(["rock","paper","scissor"]).to include(game.choose_sign)
end
#2
1
I would suggest to test the logic rather than particular value being return. You can test for rerun value not being nil or not being empty. Sample method will return random value from array which will make harder for you to pass test everytime. Hope it helps.
我建议测试逻辑而不是返回特定值。您可以测试重新运行值不是nil或不为空。 Sample方法将从数组中返回随机值,这将使您每次都难以通过测试。希望能帮助到你。