Skip to content

Commit 8918856

Browse files
committed
Add ProviderCodeGenerator to handle provider code duplicates in tests
Move to a class so we can properly organise the code. Get the provider code first and then attempt to generate an unique provider code. I used #to_set Why .to_set? Set uses hash-based lookups, which are O(1) (constant time).
1 parent 7672708 commit 8918856

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

spec/factories/providers.rb

+1-4
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,7 @@
55
provider_name { "ACME SCITT#{rand(1_000_000)}" }
66

77
sequence(:provider_code) do |n|
8-
loop do
9-
code = format("#{('A'..'Z').to_a.sample}%02d", n % 100)
10-
break code unless Provider.exists?(provider_code: code)
11-
end
8+
ProviderCodeGenerator.new(n).call
129
end
1310

1411
trait :with_anonymised_data do
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# frozen_string_literal: true
2+
3+
class ProviderCodeGenerator
4+
def initialize(sequence_number)
5+
@sequence_number = sequence_number
6+
@existing_codes = Provider.pluck(:provider_code).to_set
7+
end
8+
9+
def call
10+
attempt_count = 0
11+
possible_code = nil
12+
13+
until possible_code && @existing_codes.exclude?(possible_code)
14+
possible_code = format("#{('A'..'Z').to_a.sample}%02d", @sequence_number % 100)
15+
16+
if @existing_codes.include?(possible_code)
17+
attempt_count += 1
18+
Rails.logger.warn("ProviderCodeGenerator: Collision detected for #{possible_code}, retrying (attempt ##{attempt_count})")
19+
end
20+
end
21+
22+
possible_code
23+
end
24+
end

0 commit comments

Comments
 (0)