Skip to content

Commit

Permalink
Fix number(digits: 1) always returns 0 (#1712)
Browse files Browse the repository at this point in the history
* Fix number(digits: 1) always returns 0

Fixes #1705

* remove unnecessary Base
  • Loading branch information
ianlet authored and vbrazo committed Aug 31, 2019
1 parent dc9e62f commit 2cf87a1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 15 deletions.
2 changes: 1 addition & 1 deletion lib/faker/default/number.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def number(legacy_digits = NOT_GIVEN, digits: 10)
end

return if digits < 1
return 0 if digits == 1
return rand(0..9).round if digits == 1

# Ensure the first digit is not zero
([non_zero_digit] + generate(digits - 1)).join.to_i
Expand Down
27 changes: 13 additions & 14 deletions test/faker/default/test_faker_number.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,20 @@ def test_number
assert @tester.number(digits: 1).to_s.length == 1
end

def test_number_with_one_digit
random_number = 4
in_range = lambda { |range|
assert_equal(0..9, range)
random_number
}

Faker::Base.stub(:rand, in_range) do
assert_equal(random_number, @tester.number(digits: 1))
end
end

def test_decimal
assert @tester.decimal(l_digits: 1, r_digits: 1).to_s.match(/[0-9]{1}\.[0-9]{1}/)
assert @tester.decimal(l_digits: 2).to_s.match(/[0-9]{2}\.[0-9]{2}/)
assert @tester.decimal(l_digits: 4, r_digits: 5).to_s.match(/[0-9]{4}\.[0-9]{5}/)
end
Expand Down Expand Up @@ -115,18 +128,4 @@ def test_hexadecimal
assert @tester.hexadecimal(digits: 4).match(/[0-9a-f]{4}/)
assert @tester.hexadecimal(digits: 7).match(/[0-9a-f]{7}/)
end

def test_insignificant_zero
@tester.stub :digit, 0 do
assert_equal '0', @tester.number(digits: 1).to_s
100.times do
assert_match(/^[1-9]0/, @tester.number(digits: 2).to_s)
end

assert_equal 0.0, @tester.decimal(l_digits: 1, r_digits: 1)
100.times do
assert_match(/^0\.0[1-9]/, @tester.decimal(l_digits: 1, r_digits: 2).to_s)
end
end
end
end

0 comments on commit 2cf87a1

Please sign in to comment.