DEV Community

Luiz Eduardo Kowalski
Luiz Eduardo Kowalski

Posted on

Mocking a class with Minitest without an extra gem

I have a job that does only one thing: it runs this method

def perform
  PgHero.capture_query_stats
end
Enter fullscreen mode Exit fullscreen mode

Now, on testing, I don't really want to execute capture_query_stats, I just need to ensure the method was invoked.

I tried to stub capture_query_stats using PgHero.stub(:capture_query_stats, true), but still, not exactly what I wanted since I can't verify if a stub was called or not; only a mock can do that.

I found different gems that could do something like that, but I wanted to see if I could do this without any gem, and it turns out, I can!

I can use stub_const helper to stub the actual PgHero class and return a mock object with capture_query_stats and then verify the mock:

test "captures query stats" do
  mock = Minitest::Mock.new
  mock.expect :capture_query_stats, true

  stub_const(Object, :PgHero, mock) do
    CaptureQueryStatsJob.perform_now

    mock.verify
  end
end
Enter fullscreen mode Exit fullscreen mode

No additional gem, only what Rails provides

Top comments (0)