diff --git a/lib/faker/default/json.rb b/lib/faker/default/json.rb index 8edf1a9948..6b0dad5c0f 100644 --- a/lib/faker/default/json.rb +++ b/lib/faker/default/json.rb @@ -86,7 +86,10 @@ def build_shallow_hash(width, options) value = options[:value] hash = {} - width.times do + # retry on duplicate + (width * 10).times do + break if hash.size == width + hash[eval(key)] = eval(value) end hash diff --git a/test/faker/default/test_faker_json.rb b/test/faker/default/test_faker_json.rb index a768329a2f..9bb0733569 100644 --- a/test/faker/default/test_faker_json.rb +++ b/test/faker/default/test_faker_json.rb @@ -1,10 +1,19 @@ # frozen_string_literal: true +require 'minitest/mock' require_relative '../../test_helper' class TestFakerJson < Test::Unit::TestCase require 'json' + def test_shallow_json_keeps_width_when_keys_collide + Faker::Config.stub :random, Random.new(0) do + json = Faker::Json.shallow_json(width: 2, options: { key: 'Boolean.boolean', value: 'Boolean.boolean' }) + + assert_equal 2, JSON.parse(json).size + end + end + def test_simple_json_lenght expected_result_length = JSON.parse(simple_json).flatten.length