Torbjörn Torbjörn - 4 months ago 17
Ruby Question

How to mock Ruby Module functions?



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?

Answer

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 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
Comments