TIL: Mocking with Minitest in Ruby 2.0+
I normally work within an RSpec testing envionment, but I definitely enjoy working with more traditional Test::Unit tests when I get the chance.
Today I discovered that Minitest, the testing toolkit that has been part of the Ruby standard library since 2.0 has built-in support for mocks and stubs.
To use this in a Test::Unit test, simply
It looks like a mock object has to be specifically made. Minitest/Mocks does not include double support - you’ll need something like Mocha for that. The method signature on Minitest::Mock is:
expect(:method_name, return_value, [args]).
Here’s an example:
A major difference from Rspec mocks to be aware of is that the
verify method must be called on the mock object to actually check that the expected methods were returned.
Minitest also includes basic support for stubs. The method signature for stubs is:
ObjectUnderTest.stub(:method_name, stub_value, &block). Minitest does not have an unstub method - instead, it is expected that the test code that requires the stub should go inside the block passed to
stub, and minitest will automatically unstub when the block completes.
message_sender = MessageSender.new message_sender.stub(:perform_deliveries?, true) do message_sneder.send_message(email: "[email protected]", message: "Test") end