Within my test I want to stub a canned response for any instance of a class.
It might look like something like:
Book.stubs(:title).any_instance().returns("War and Peace")
Then whenever I call @book.title
it returns "War and Peace".
Is there a way to do this within MiniTest? If yes, can you give me an example code snippet?
Or do I need something like mocha?
MiniTest does support Mocks but Mocks are overkill for what I need.
Stubbing in Minitest is done by calling . stub on the object/class that you want to stub a method on, with three arguments: the method name, the return value of the stub and a block. The block is basically the scope of the stub, or in other words, the stub will work only in the provided block.
Stub. Definition of stub: A method stub is an instruction to an object (real or test double) to return a. known value in response to a message.
You use mocks to test the interaction between two objects. Instead of testing the output value, like in a regular expectation. For example: You're writing an API that flips images. Instead of writing your own image-manipulation code you use a gem like mini_magick .
Minitest is the default testing suite used with Rails, so no further setup is required to get it to work.
# Create a mock object book = MiniTest::Mock.new # Set the mock to expect :title, return "War and Piece" # (note that unless we call book.verify, minitest will # not check that :title was called) book.expect :title, "War and Piece" # Stub Book.new to return the mock object # (only within the scope of the block) Book.stub :new, book do wp = Book.new # returns the mock object wp.title # => "War and Piece" end
I use minitest for all my Gems testing, but do all my stubs with mocha, it might be possible to do all in minitest with Mocks(there is no stubs or anything else, but mocks are pretty powerful), but I find mocha does a great job, if it helps:
require 'mocha' Books.any_instance.stubs(:title).returns("War and Peace")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With