How can I mock module functions of a self-written module inside my project?
Given the module and function
module ModuleA::ModuleB
def self.my_function( arg )
end
end
which is called like
ModuleA::ModuleB::my_function( with_args )
How should I mock it when it's used inside a function I'm writing specs for?
Doubling it (obj = double("ModuleA::ModuleB")
) makes no sense for me as the function is called on the module and not on an object.
I've tried stubbing it (ModuleA::ModuleB.stub(:my_function).with(arg).and_return(something)
). Obviously, it did not work. stub
is not defined there.
Then I've tried it with should_receive
. Again NoMethodError
.
What is the preferred way of mocking a module and it's functions?
For rspec 3.6 see How to mock class method in RSpec expect syntax?
To avoid link-only-answer, here is copy of answer by Andrey Deineko:
allow(Module)
.to receive(:profile)
.with("token")
.and_return({"name" => "Hello", "id" => "14314141", "email" => "[email protected]"})
Given the module you describe in your question
module ModuleA ; end
module ModuleA::ModuleB
def self.my_function( arg )
end
end
and the function under test, which calls the module function
def foo(arg)
ModuleA::ModuleB.my_function(arg)
end
then you can test that foo
calls myfunction
like this:
describe :foo do
it "should delegate to myfunction" do
arg = mock 'arg'
result = mock 'result'
ModuleA::ModuleB.should_receive(:my_function).with(arg).and_return(result)
foo(arg).should == result
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With