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
  'end'
 end

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

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

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: https://www.ruby-forum.com/t/modules-and-stub/168721

    The solution code looks like this:

    MyModule.stub(:my_method).and_return('not_bla')
    

    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:

    MyModule.stub(:my_method).and_return('not_bla')
    

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