Home > Back-end >  How to mock module static method in ruby rspec?
How to mock module static method in ruby rspec?

Time:05-07

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!

CodePudding user response:

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

CodePudding user response:

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?

  • Related