随机化可以在测试运行之间复制

在 Ruby 中,随机化通过调用 `srand` 并传递要使用的种子来进行播种。通过这样做,随后对 `rand`、`shuffle`、`sample` 等的调用在传递相同的种子给 `srand` 的情况下,都会以相同的方式随机化。

RSpec 注意在采取涉及随机性的操作(例如示例的随机排序)时,不要直接播种随机化。

由于 RSpec 从不调用 `srand`,这意味着您可以自由选择使用哪种机制(如果有)来播种随机化。

下面是一个示例,说明如何在需要时使用 RSpec 的种子来实现此目的。

如果您想在没有任何 RSpec 帮助的情况下管理播种随机化,请牢记以下事项

* The seed should never be hard-coded.

  The first example below only does this to show that seeding randomization
  with a seed other than the one used by RSpec will correctly seed
  randomization.

* Report the seed that was chosen.

  The randomization that was used for a given test run can not be reproduced
  if no one knows what seed was used to begin with.

* Provide a mechanism to feed the seed into the tests.

  Without this, the call to `srand` will have to be hard-coded any time it
  is necessary to replicate a given test run's randomness.

背景

给定一个名为“.rspec”的文件,其中包含

--require spec_helper

给定一个名为“spec/random_spec.rb”的文件,其中包含

RSpec.describe 'randomized example' do
  it 'prints random numbers' do
    puts 5.times.map { rand(99) }.join("-")
  end
end

使用 `srand` 指定种子提供可预测的随机化

给定一个名为“spec/spec_helper.rb”的文件,其中包含

srand 123

我运行 `rspec`

然后输出应包含“66-92-98-17-83”。

将 RSpec 种子传递给 `srand` 提供可预测的随机化

给定一个名为“spec/spec_helper.rb”的文件,其中包含

srand RSpec.configuration.seed

我运行 `rspec --seed 123`

然后输出应包含“66-92-98-17-83”。