The answer is to expect
method, :call
, instead of expect
ing method, connect_and_send
. The following code:
require 'minitest/autorun'
module Email
def self.connect_and_send(*args)
nil
end
end
class Test < Minitest::Test
def test_it
fake = Minitest::Mock.new
fake.expect :call, nil, ['a', 'b', 'c']
Email.stub :connect_and_send, fake do
Email.connect_and_send 'a', 'b', 'z'
end
fake.verify
end
end
verifies, in the desired way, which arguments were passed to the method, connect_and_send
.
It gives the proper error message, that the stubbed method was passed the incorrect arguments:
1) Error:
Test#test_it:
MockExpectationError: mocked method :call called with unexpected arguments ["a", "b", "z"]
-:12:in 'block in test_it'
-:11:in 'test_it'
1 runs, 0 assertions, 0 failures, 1 errors, 0 skips
And it proves that the code under test invoked the method, connect_and_send
.
If an object has multiple methods you wish to stub—while verifying their arguments—then use more than one mock.
Here's Minitest's documentation of Object#stub
. Technically it's correct, when it says of its second parameter (see the third line):
#stub(name, val_or_callable, *block_args) ⇒ Object
Add a temporary stubbed method replacing name for the duration of the block.
If val_or_callable responds to #call, then it returns the result of calling it[.]
Yet, I suppose that many people (as did I) will misread the documentation in this phrase as meaning, instead, a "call" to the stubbed method, such as—in this example—the connect_and_send
method. Why? Because:
In the third line, the word, 'call' has two meanings; and
The hash character #
in #call
slightly resembles each of the letters E, H, and T, which are all that's required, in order to misread #call
as:
If val_or_callable responds to the call, then it returns the result of calling it[.]
Anyway, the documentation IMO would be improved by adding the word, "method":
If val_or_callable has a #call method, then it returns the result of invoking it[.]
To me, the examples in the Minitest documentation (in Object#stub and Mock) perhaps seem somewhat incomplete, when mocking and stubbing are combined.
Again, when you verify arguments passed to your mock (using Minitest), you should expect
method :call
, instead of expect
ing the method you're stubbing!