Skip to content

Commit

Permalink
Mock#expects,#stubs should return last expectation
Browse files Browse the repository at this point in the history
Even when passed a hash of method names vs return values. This is the
same behaviour as for ObjectMethods#expects & #stubs and the behaviour
described by the documentation for Mock#expects & #stubs.

Fixes freerange#524.
  • Loading branch information
floehopper committed Apr 20, 2022
1 parent d446657 commit b6b637d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/mocha/mock.rb
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ class Mock
# object.expects(:expected_method_one).returns(:result_one)
# object.expects(:expected_method_two).returns(:result_two)
def expects(method_name_or_hash, backtrace = nil)
expectation = nil
iterator = ArgumentIterator.new(method_name_or_hash)
iterator.each do |*args|
method_name = args.shift
Expand All @@ -117,6 +118,7 @@ def expects(method_name_or_hash, backtrace = nil)
expectation.returns(args.shift) unless args.empty?
@expectations.add(expectation)
end
expectation
end

# Adds an expectation that the specified method may be called any number of times with any parameters.
Expand Down Expand Up @@ -145,6 +147,7 @@ def expects(method_name_or_hash, backtrace = nil)
# object.stubs(:stubbed_method_one).returns(:result_one)
# object.stubs(:stubbed_method_two).returns(:result_two)
def stubs(method_name_or_hash, backtrace = nil)
expectation = nil
iterator = ArgumentIterator.new(method_name_or_hash)
iterator.each do |*args|
method_name = args.shift
Expand All @@ -154,6 +157,7 @@ def stubs(method_name_or_hash, backtrace = nil)
expectation.returns(args.shift) unless args.empty?
@expectations.add(expectation)
end
expectation
end

# Removes the specified stubbed methods (added by calls to {#expects} or {#stubs}) and all expectations associated with them.
Expand Down
35 changes: 35 additions & 0 deletions test/acceptance/issue_524_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
require File.expand_path('../acceptance_test_helper', __FILE__)

class Issue524Test < Mocha::TestCase
include AcceptanceTest

def setup
setup_acceptance_test
end

def teardown
teardown_acceptance_test
end

def test_expects_returns_last_expectation
test_result = run_as_test do
object = mock
object.expects(:method_1 => 1, :method_2 => 2).twice
object.method_1
object.method_2
object.method_2
end
assert_passed(test_result)
end

def test_stubs_returns_last_expectation
test_result = run_as_test do
object = mock
object.stubs(:method_1 => 1, :method_2 => 2).twice
object.method_1
object.method_2
object.method_2
end
assert_passed(test_result)
end
end

0 comments on commit b6b637d

Please sign in to comment.