Skip to content

Commit

Permalink
Fix regression when stubbed method invoked with no args
Browse files Browse the repository at this point in the history
In this commit [1] which was part of #660 and was released in v2.4.3,
the new code didn't take into account that the `parameter` local
variable in `HasEntries#matches?` can be `nil` if the stubbed method
expects a `Hash` or keyword arguments but is called with no arguments.

Previously this wasn't a problem, because the `nil` was handled by this
guard condition [2] in `HasEntry#matches?`. However, now we're calling
`#length` on `parameter` when `exact` is `true`, we need this new guard
condition in `HasEntries#matches?`.

[1]: 5e6a07b
[2]: https://github.com/freerange/mocha/blob/e95fda25c41faaa4a7737b62a471544c5c2ddf2f/lib/mocha/parameter_matchers/has_entry.rb#L68
  • Loading branch information
floehopper committed Jul 23, 2024
1 parent e95fda2 commit 869c24e
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/mocha/parameter_matchers/has_entries.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ def initialize(entries, exact: false)
# @private
def matches?(available_parameters)
parameter = available_parameters.shift
return false unless parameter
return false if @exact && @entries.length != parameter.length

has_entry_matchers = @entries.map { |key, value| HasEntry.new(key, value) }
Expand Down
9 changes: 9 additions & 0 deletions test/acceptance/parameter_matcher_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,15 @@ def test_should_not_match_hash_parameter_which_is_not_exactly_the_same
assert_failed(test_result)
end

def test_should_not_match_hash_parameter_when_method_invoked_with_no_parameters
test_result = run_as_test do
mock = mock()
mock.expects(:method).with(key_1: 'value_1')
mock.method
end
assert_failed(test_result)
end

def test_should_match_hash_parameter_with_specified_key
test_result = run_as_test do
mock = mock()
Expand Down
10 changes: 10 additions & 0 deletions test/unit/parameter_matchers/has_entries_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ def test_should_not_match_hash_not_including_specified_entries
assert !matcher.matches?([{ key_1: 'value_1', key_2: 'value_2' }])
end

def test_should_not_match_no_arguments_when_exact_match_not_required
matcher = has_entries(key_1: 'value_1')
assert !matcher.matches?([nil])
end

def test_should_not_match_no_arguments_when_exact_match_required
matcher = HasEntries.new({ key_1: 'value_1' }, exact: true)
assert !matcher.matches?([nil])
end

def test_should_describe_matcher
matcher = has_entries(key_1: 'value_1', key_2: 'value_2')
description = matcher.mocha_inspect
Expand Down

0 comments on commit 869c24e

Please sign in to comment.