DEV Community

Jaap Groeneveld
Jaap Groeneveld

Posted on • Edited on

How to use minitest/mock to mock any instance

stub_any_instance is a very helpful utility in common mocking frameworks. minitest/mock does not provide this but its very simple to provide a similar effect.

Mocking/Stubbing arbitrary instances of classes is very helpful in testing. In ruby it's easy to do this even without using some sort of dependency injection.

Let's do it!

Lets assume we have a Fetcher class that needs an instance of ApiClient

class Fetcher
  def fetch_data
    ApiClient.new.get("https://service.com/api/data")
  end
end
Enter fullscreen mode Exit fullscreen mode

We start by creating a mock and setting the relevant expectations like always.

mock_api_client = Minitest::Mock.new
mock_api_client.expect(:get, {data: "return-data"}, ["https://service.com/api/data"])
Enter fullscreen mode Exit fullscreen mode

Now we need to make this mock the instance that some class would instantiate by stubbing the class method .new

ApiClient.stub(:new, mock_api_client) do
  result = Fetcher.new.fetch_data
  assert_equal {data: "return-data"}, result
end
Enter fullscreen mode Exit fullscreen mode

The mock/stub combination would be active during the duration of the block.

Top comments (0)