This content originally appeared on DEV Community and was authored by DEV Community
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
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"])
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
The mock/stub combination would be active during the duration of the block.
This content originally appeared on DEV Community and was authored by DEV Community
DEV Community | Sciencx (2022-03-02T14:27:31+00:00) How to use minitest/mock to mock any instance. Retrieved from https://www.scien.cx/2022/03/02/how-to-use-minitest-mock-to-mock-any-instance/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.