Skip to content

Commit

Permalink
Fix misleading exception message in ParameterMatchers#has_entry
Browse files Browse the repository at this point in the history
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).
  • Loading branch information
cstyles authored and floehopper committed Jun 18, 2021
1 parent c98c6ec commit 9c4ef13
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 13 deletions.
35 changes: 22 additions & 13 deletions lib/mocha/parameter_matchers/has_entry.rb
Expand Up @@ -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
Expand Down Expand Up @@ -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
5 changes: 5 additions & 0 deletions test/unit/parameter_matchers/has_entry_test.rb
Expand Up @@ -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')
Expand Down

0 comments on commit 9c4ef13

Please sign in to comment.