Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 780
Torbjörn Avatar asked Jul 05 '12 21:07

Torbjörn


2 Answers

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]"})
like image 110
reducing activity Avatar answered Oct 18 '22 02:10

reducing activity


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
like image 30
Wayne Conrad Avatar answered Oct 18 '22 02:10

Wayne Conrad