简体   繁体   English

如何模拟Ruby模块功能?

[英]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. 加倍它( obj = double("ModuleA::ModuleB") )对我来说没有意义,因为函数是在模块上调用而不是在对象上调用。

I've tried stubbing it ( ModuleA::ModuleB.stub(:my_function).with(arg).and_return(something) ). 我已经尝试过它( ModuleA::ModuleB.stub(:my_function).with(arg).and_return(something) )。 Obviously, it did not work. 显然,它没有用。 stub is not defined there. stub没有在那里定义。

Then I've tried it with should_receive . 然后我用should_receive尝试了它。 Again NoMethodError . 再次NoMethodError

What is the preferred way of mocking a module and it's functions? 模拟模块及其功能的首选方法是什么?

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: 然后你可以测试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

For rspec 3.6 see How to mock class method in RSpec expect syntax? 对于rspec 3.6,请参阅如何在RSpec期望语法中模拟类方法?

To avoid link-only-answer, here is copy of answer by Andrey Deineko: 为了避免仅链接答案,这里是Andrey Deineko的答案副本:

allow(Module)
  .to receive(:profile)
  .with("token")
  .and_return({"name" => "Hello", "id" => "14314141", "email" => "hello@me.com"})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM