如何模拟Ruby模块功能?

Tor*_*örn 11 ruby rspec module mocking

如何在项目中模拟自编写模块的模块功能?

鉴于模块和功能

module ModuleA::ModuleB
  def self.my_function( arg )
  end
end
Run Code Online (Sandbox Code Playgroud)

这就是所谓的

ModuleA::ModuleB::my_function( with_args )
Run Code Online (Sandbox Code Playgroud)

当我在编写规范的函数中使用它时,我应该如何模拟它?


加倍它(obj = double("ModuleA::ModuleB"))对我来说没有意义,因为函数是在模块上调用而不是在对象上调用.

我试过抄袭它(ModuleA::ModuleB.stub(:my_function).with(arg).and_return(something)).显然,它没有用.stub那里没有定义.

然后我试了一下should_receive.再次NoMethodError.

模拟模块及其功能的首选方法是什么?

Way*_*rad 11

给出您在问题中描述的模块

module ModuleA ; end

module ModuleA::ModuleB
  def self.my_function( arg )
  end
end
Run Code Online (Sandbox Code Playgroud)

和被测函数,它调用模块函数

def foo(arg)
  ModuleA::ModuleB.my_function(arg)
end
Run Code Online (Sandbox Code Playgroud)

那么你可以测试这样的foo调用myfunction:

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
Run Code Online (Sandbox Code Playgroud)