wasabigeek

Mocking in RSpec VS Minitest: A Cheatsheet

January 05, 2022

My first exposure to a testing library in Ruby and Rails was 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()
Note:
mock = Minitest::Mock.new
mock.expect(:method, args, return)
mock.verify
Note: cannot call expect on any Object, but can 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 val_or_callable
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!

Footnotes

  • For the curious, I wrote about how minitest/mock works here

Related Posts

Reading a Ruby gem with VSCode

Practical Metaprogramming in Ruby: minitest/mock

How does ActiveRecord know the primary_key?

Comments


Nick

By Nick, a Business grad turned Software Engineer, living in sunny 🇸🇬. I write mostly about Ruby and Rails, not wasabi (sorry!).