diff --git a/lib/faker/nhs.rb b/lib/faker/nhs.rb index 007eebe6e0..b6a7be7828 100644 --- a/lib/faker/nhs.rb +++ b/lib/faker/nhs.rb @@ -4,7 +4,10 @@ module Faker class NationalHealthService < Base class << self def british_number - base_number = rand(400_000_000...499_999_999) + base_number = rand(400_000_001...499_999_999) + # If the check digit is equivalent to 10, the number is invalid. + # See https://en.wikipedia.org/wiki/NHS_number + base_number -= 1 if check_digit(base_number) == 10 "#{base_number}#{check_digit(base_number)}".to_s .chars .insert(3, ' ') @@ -18,7 +21,13 @@ def check_digit(number = 0) position = idx + 1 sum += (digit.to_i * (11 - position)) end - 11 - (sum % 11) + result = 11 - (sum % 11) + + # A value of 11 is considered the same as 0 + # See https://en.wikipedia.org/wiki/NHS_number + return 0 if result == 11 + + result end end end diff --git a/test/test_faker_national_health_service.rb b/test/test_faker_national_health_service.rb index c5d0630cc9..a915eb3016 100644 --- a/test/test_faker_national_health_service.rb +++ b/test/test_faker_national_health_service.rb @@ -8,12 +8,20 @@ def setup end def test_nhs_british_number - omit 'fix me' - assert_match(/\A\d{3}\s\d{3}\s\d{4}\z/, @tester.british_number) end + def test_nhs_check_digit_equals_10 + Faker::NationalHealthService.stub(:rand, 458_617_434) do + assert_match('458 617 4331', @tester.british_number) + end + end + def test_nhs_check_digit assert_equal 6, @tester.check_digit(400_012_114) end + + def test_nhs_check_digit_11 + assert_equal 0, @tester.check_digit(418_513_625) + end end