Skip to content

Commit c37ab30

Browse files
committed
Configure CEfE generator randomness with RSpec seed
We still have at least one flakey spec [1] and I noticed it depends on the `verified_school` factory which uses the `ForEducationCodeGenerator.generate` method to set the `School#code`. On the offchance this is causing some kind of non-deterministic problem and to make that generator more deterministic in specs, I thought it would be worthwhile using the RSpec seed to seed the random number generator (RNG) used by `ForEducationCodeGenerator.generate`. The changes in this commit allow the RNG to be overridden and adds file in `spec/support` to do this in specs so it uses the RSpec seed. [1]: https://github.com/RaspberryPiFoundation/editor-api/blob/f397e870f2a33cce1f53b9104c52314f5233572c/spec/concepts/school_teacher/invite_spec.rb#L14-L17
1 parent 08936b1 commit c37ab30

File tree

3 files changed

+14
-4
lines changed

3 files changed

+14
-4
lines changed

lib/for_education_code_generator.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,12 @@
33
class ForEducationCodeGenerator
44
MAX_CODE = 1_000_000
55

6+
cattr_accessor :random
7+
8+
self.random ||= Random.new
9+
610
def self.generate
7-
number = Random.new.rand(MAX_CODE)
11+
number = random.rand(MAX_CODE)
812
code = format('%06d', number)
913

1014
code.match(/(\d\d)(\d\d)(\d\d)/) do |m|

spec/lib/for_education_code_generator_spec.rb

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,7 @@
55
RSpec.describe ForEducationCodeGenerator do
66
describe '.generate' do
77
it 'uses Random#rand to generate a random number up to the maximum' do
8-
random = instance_double(Random)
9-
allow(random).to receive(:rand).with(ForEducationCodeGenerator::MAX_CODE).and_return(123)
10-
allow(Random).to receive(:new).and_return(random)
8+
allow(described_class.random).to receive(:rand).with(ForEducationCodeGenerator::MAX_CODE).and_return(123)
119

1210
expect(described_class.generate).to eq('00-01-23')
1311
end
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# frozen_string_literal: true
2+
3+
RSpec.configure do |config|
4+
config.before(:suite) do
5+
puts "ForEducationCodeGenerator randomized with seed #{config.seed}"
6+
ForEducationCodeGenerator.random = Random.new(config.seed)
7+
end
8+
end

0 commit comments

Comments
 (0)