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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay