From 9c4ef13197300d6edd1990dabd3df00385e40d98 Mon Sep 17 00:00:00 2001 From: Collin Styles Date: Sat, 12 Jun 2021 13:13:40 -0700 Subject: [PATCH] Fix misleading exception message in ParameterMatchers#has_entry PR: #513 Previously if has_entry was called without any arguments, it raised the following exception: ArgumentError: Too many arguments; use either a single argument (must be a Hash) or two arguments (a key and a value). --- lib/mocha/parameter_matchers/has_entry.rb | 35 ++++++++++++------- .../unit/parameter_matchers/has_entry_test.rb | 5 +++ 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/lib/mocha/parameter_matchers/has_entry.rb b/lib/mocha/parameter_matchers/has_entry.rb index e511d2363..6bf9a22e6 100644 --- a/lib/mocha/parameter_matchers/has_entry.rb +++ b/lib/mocha/parameter_matchers/has_entry.rb @@ -42,20 +42,10 @@ module ParameterMatchers # def has_entry(*options) # rubocop:disable Naming/PredicateName case options.length + when 0 + raise ArgumentError, 'No arguments. Expecting at least one.' when 1 - case options[0] - when Hash - case options[0].length - when 0 - raise ArgumentError, 'Argument has no entries.' - when 1 - key, value = options[0].first - else - raise ArgumentError, 'Argument has multiple entries. Use Mocha::ParameterMatchers#has_entries instead.' - end - else - raise ArgumentError, 'Argument is not a Hash.' - end + key, value = parse_option(options[0]) when 2 key, value = options else @@ -85,5 +75,24 @@ def mocha_inspect "has_entry(#{@key.mocha_inspect} => #{@value.mocha_inspect})" end end + + private + + # @private + def parse_option(option) + case option + when Hash + case option.length + when 0 + raise ArgumentError, 'Argument has no entries.' + when 1 + option.first + else + raise ArgumentError, 'Argument has multiple entries. Use Mocha::ParameterMatchers#has_entries instead.' + end + else + raise ArgumentError, 'Argument is not a Hash.' + end + end end end diff --git a/test/unit/parameter_matchers/has_entry_test.rb b/test/unit/parameter_matchers/has_entry_test.rb index 8526620bb..feff6c40b 100644 --- a/test/unit/parameter_matchers/has_entry_test.rb +++ b/test/unit/parameter_matchers/has_entry_test.rb @@ -92,6 +92,11 @@ def test_should_raise_argument_error_if_no_entries_are_supplied assert_equal 'Argument has no entries.', e.message end + def test_should_raise_argument_error_if_no_arguments_are_supplied + e = assert_raises(ArgumentError) { has_entry } + assert_equal 'No arguments. Expecting at least one.', e.message + end + def test_should_raise_argument_error_if_multiple_entries_are_supplied e = assert_raises(ArgumentError) do has_entry(:key_1 => 'value_1', :key_2 => 'value_2')