jessica dussault

Minitest stubs

Date
1 October, 2025
Category
code
Tags
will need again testing Ruby on Rails

Oh my gosh, once again, I find myself looking at the same darn webpages trying to remember how stubbing works in Minitest. I do not find it intuitive. So rather than me having to try and find a test I previously wrote, I'm just going to stick some things here.

I don't actually know if these are right because I didn't test them for this post about tests. They probably have a silly typo or are just plain wrong. You really shouldn't trust me with stubbing tests, is what I'm saying. But if you are me in the future, I hope this helps:

Class methods

# my actual module

module Some::Module
  def self.fetch
    ...
  end
end

# in my test

Some::Module.stub :fetch, "fake_fetch_response" do
  # inside of here, use some code that expects .fetch to return that string
  assert ...
end

Checking the parameters

With positional args, you will need to use .expect(:call) and give it an array of the arguments it should be checking. Don't forget to add .verify at the end!

module Some::Module
  def self.fetch(id)
end

fake = Minitest::Mock.new
fake.expect(:call, "fake_fetch_response", ["some_id"])
Some::Module.stub :fetch, fake do
  ...code that calls .fetch...
end
fake.verify

If you need keyword args, it's the same as above but:

fake.expect(:call, "fake_fetch_response", [], keyword_arg: "some_arg")

Instance methods

# the actual class

class SomeClass
  attr_reader :code, :info

  def initialize(res)
    @code = res.code
    @info = parse_info(res.json)
    ...
  end
end

# in my test

# consider naming this something specific, like "fake_response"
# and use .expect to define responses to different instance methods
instance = Minitest::Mock.new
instance.expect(:code, 200)
instance.expect(:json, { ... })

# use your instance method in some test
thing = SomeClass.new(instance)
assert_equal 200, thing.code
assert_equal ..., thing.info