Skip to content

Commit

Permalink
NHS: fix occasional bad numbers (faker-ruby#1425)
Browse files Browse the repository at this point in the history
* Add additional tests around NHS number edge cases

* Add code to handle check digit 10 and 11 edge cases
  • Loading branch information
ChaoticBoredom authored and vbrazo committed Oct 20, 2018
1 parent 977fa68 commit f114a18
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
13 changes: 11 additions & 2 deletions lib/faker/nhs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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, ' ')
Expand All @@ -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
Expand Down
12 changes: 10 additions & 2 deletions test/test_faker_national_health_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit f114a18

Please sign in to comment.