How to mock module static method in ruby rspec?

I am trying to write some rspec tests and I want to mock a static method from a module.

The setup is like this:

module MyModule

 def self.my_method

and inside rspec I want to mock my_method, like this:


Inside the working code, the method is called like this: MyModule.my_method

When I try to use the setup from above, it gives me the following error:

MyModule does not implement #my_method

Thank you!

2 answers

  • answered 2022-05-06 14:51 Mihai

    I found the answer here:

    The solution code looks like this:


    I could not find something similar on stackoverflow. Should I delete this question?

  • answered 2022-05-06 15:32 spickermann

    The new syntax to stub messages in RSpec looks like this:

    allow(MyModule).to receive(:my_method).and_return('not_bla')

    The old syntax which is not recommended anymore looks like this:


How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum