'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!
Solution 1:[1]
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')
Solution 2:[2]
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | spickermann |
Solution 2 | Mihai |