Mocking in RSpec VS Minitest: A Cheatsheet

January 05, 2022

My first exposure to testing in Ruby / Rails was through RSpec, but I’m now using Minitest. It wasn’t immediately obvious how to translate rspec-expectations and rspec-mocks to Minitest, so here’s my attempt at a cheatsheet:

RSpec minitest with mocha minitest with minitest/mocks
double mock or stub Minitest::Mock.new
instance_double stub or mock.responds_like_instance_of Not supported
expect().to receive().with().and_return() mock.expects().with().returns()
  • like RSpec, can also call expects on any object, not just a Mock/Stub
  • with has limited keyword arg support
mock = Minitest::Mock.new
mock.expect(:method, args, return)
Note: cannot call expect on any Object, but make a Mock delegate to an underlying object
expect().not_to receive() mock.expects().never Technically you could use Object#stub and raise in the valorcallable
expect()... and yield_control() mock.expects().yields(*parameters)
See docs
Not supported since return value is not a callable
expect()... and raise_error() mock.expects().raises(error)
See docs
Can pass in a block (instead of expected args) to expect and raise there
allow()... Similar as above but substitute expects with stubs Can use Object#stub
.and_call_original Not supported (see reasoning) Not supported
allow_any_instance_of.Klass Klass.any_instance.stubs Not supported

It’s very possible I’ve gotten something wrong - please feel free to correct in the comments or submit a PR!


Written by Nick who is a indie-hacker wannabe, living in sunny Singapore. Twitter | GitHub