Just to further explain @panic's answer , suppose you have a Book class:
require 'minitest/mock' class Book; end
First, create a stub for the Book instance and make it return the desired title (any number of times):
book_instance_stub = Minitest::Mock.new def book_instance_stub.title desired_title = 'War and Peace' return_value = desired_title return_value end
Then make the Book class instantiate your Book instance (only and always, in the following block of code):
method_to_redefine = :new return_value = book_instance_stub Book.stub method_to_redefine, return_value do ...
Inside this block of code (only), the Book::new method is a stub. Let's try this:
... some_book = Book.new another_book = Book.new puts some_book.title
Or, briefly:
require 'minitest/mock' class Book; end instance = Minitest::Mock.new def instance.title() 'War and Peace' end Book.stub :new, instance do book = Book.new another_book = Book.new puts book.title
Alternatively, you can set the extension gem minitest-stub_any_instance . (Note: when using this approach, the Book#title method must exist before you drown it.) Now you can say more simply:
require 'minitest/stub_any_instance' class Book; def title() end end desired_title = 'War and Peace' Book.stub_any_instance :title, desired_title do book = Book.new another_book = Book.new puts book.title
If you want to make sure that Book#title is called a certain number of times, do:
require 'minitest/mock' class Book; end book_instance_stub = Minitest::Mock.new method = :title desired_title = 'War and Peace' return_value = desired_title number_of_title_invocations = 2 number_of_title_invocations.times do book_instance_stub.expect method, return_value end method_to_redefine = :new return_value = book_instance_stub Book.stub method_to_redefine, return_value do some_book = Book.new puts some_book.title
Thus, for any particular instance, a call to the MockExpectationError: No more expects available method MockExpectationError: No more expects available than specified, calls MockExpectationError: No more expects available .
In addition, for any particular instance, a call to the MockExpectationError: expected title() method fewer times than indicated calls MockExpectationError: expected title() , but only if you call #verify for that instance at this point.