RSpec:字符串应在数组中

and*_*ndy 1 ruby rspec

我正在测试一个随机字符串生成器,该生成器需要两个单词数组,然后从中选择随机单词。我需要能够测试它实际上是随机的。例如:

FrostyMeadow.generate(:nouns => ["hello", "world"], :adjectives => ["hello","world"]
Run Code Online (Sandbox Code Playgroud)

应该生成以下字符串之一:

["hello world", "world world", "world hello", "hello hello"]
Run Code Online (Sandbox Code Playgroud)

有什么办法可以给rspec该数组并检查生成的字符串是否在其中?

Dan*_*ans 5

随机性很难测试,但是在您的情况下,您可以通过以下方式实现它:

word = FrostyMeadow.generate(:nouns => ["hello", "world"], :adjectives => ["hello","world"]
["hello world", "world world", "world hello", "hello hello"].should include(word)
Run Code Online (Sandbox Code Playgroud)