Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

[#976] Handles zero as max for rand #978

Merged
merged 1 commit into from
Jul 12, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/faker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,13 @@ def shuffle(list)
end

def rand(max = nil)
max ? Faker::Config.random.rand(max) : Faker::Config.random.rand
if max.nil?
Faker::Config.random.rand
elsif max.is_a?(Range) || max.to_i > 0
Faker::Config.random.rand(max)
else
0
end
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/faker/lorem.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def paragraphs(paragraph_count = 3, supplemental = false)
end

def question(word_count = 4, supplemental = false, random_words_to_add = 6)
words(word_count + rand(random_words_to_add.to_i).to_i, supplemental).join(' ').capitalize + '?'
words(word_count + rand(random_words_to_add.to_i), supplemental).join(' ').capitalize + '?'
end

def questions(question_count = 3, supplemental = false)
Expand Down
26 changes: 24 additions & 2 deletions test/test_faker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,35 @@ def test_deterministic_rand_in_range
Faker::Config.random = Random.new(42)
assert v == Faker::Base.rand_in_range(0, 1000)
end


def test_rand_for_nil
assert_nothing_raised ArgumentError do
Faker::Base.rand(nil)
end
assert_nothing_raised ArgumentError do
Faker::Base.rand
end
end

def test_rand_for_zero
assert_nothing_raised ArgumentError do
Faker::Base.rand(0)
end
assert_equal 0, Faker::Base.rand(0)
end

def test_rand_for_range
assert_nothing_raised ArgumentError do
Faker::Base.rand(0..6)
end
assert_includes 0..6, Faker::Base.rand(0..6)
end

def test_unique
unique_numbers = 8.times.map do
Faker::Base.unique.numerify('#')
end

assert_equal(unique_numbers.uniq, unique_numbers)
end

end
4 changes: 4 additions & 0 deletions test/test_faker_lorem.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ def test_word
100.times { assert @standard_wordlist.include?(@tester.word) }
end

def test_exact_sentence_word_count
assert_equal 2, @tester.sentence(2, false, 0).split(' ').length
end

def test_exact_count_param
assert(@tester.characters(2).length == 2)
assert(@tester.words(2).length == 2)
Expand Down