Debian Codegraph @

rspec-core/features/command_line/randomization.feature

raw
1 Feature: Randomization can be reproduced across test runs
2
3 In Ruby, randomness is seeded by calling `srand` and passing it the seed that
4 you want to use. By doing this, subsequent calls to `rand`, `shuffle`,
5 `sample`, etc. will all be randomized the same way given the same seed is
6 passed to `srand`.
7
8 RSpec takes care not to seed randomization directly when taking action that
9 involves randomness (such as random ordering of examples).
10
11 Since RSpec does not ever invoke `srand`, this means that you are free to
12 choose which, if any, mechanism is used to seed randomization.
13
14 There is an example below of how to use RSpec's seed for this purpose if you
15 wish to do so.
16
17 If you would like to manage seeding randomization without any help from RSpec,
18 please keep the following things in mind:
19
20 * The seed should never be hard-coded.
21
22 The first example below only does this to show that seeding randomization
23 with a seed other than the one used by RSpec will correctly seed
24 randomization.
25
26 * Report the seed that was chosen.
27
28 The randomization that was used for a given test run can not be reproduced
29 if no one knows what seed was used to begin with.
30
31 * Provide a mechanism to feed the seed into the tests.
32
33 Without this, the call to `srand` will have to be hard-coded any time it
34 is necessary to replicate a given test run's randomness.
35
36 Background:
37 Given a file named ".rspec" with:
38 """
39 --require spec_helper
40 """
41
42 Given a file named "spec/random_spec.rb" with:
43 """ruby
44 RSpec.describe 'randomized example' do
45 it 'prints random numbers' do
46 puts 5.times.map { rand(99) }.join("-")
47 end
48 end
49 """
50
51 Scenario: Specifying a seed using `srand` provides predictable randomization
52 Given a file named "spec/spec_helper.rb" with:
53 """ruby
54 srand 123
55 """
56 When I run `rspec`
57 Then the output should contain "66-92-98-17-83"
58
59 Scenario: Passing the RSpec seed to `srand` provides predictable randomization
60 Given a file named "spec/spec_helper.rb" with:
61 """ruby
62 srand RSpec.configuration.seed
63 """
64 When I run `rspec --seed 123`
65 Then the output should contain "66-92-98-17-83"