Ruby-on-rails rspec 3 - 存根类方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25066699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:49:56  来源:igfitidea点击:

rspec 3 - stub a class method

ruby-on-railsrubyrspecrspec3

提问by Peter Sankauskas

I am upgrading from rspec 2.99 to rspec 3.0.3 and have converted instance methods to use allow_any_instance_of, but haven't figured out how to stub a class method. I have code like this:

我正在从 rspec 2.99 升级到 rspec 3.0.3 并将实例方法转换为 use allow_any_instance_of,但还没有弄清楚如何存根类方法。我有这样的代码:

module MyMod
  class Utils
    def self.find_x(myarg)
      # Stuff
    end
  end
end

and my rspec 2 test does this:

我的 rspec 2 测试是这样做的:

MyMod::Utils.stub(:find_x).and_return({something: 'testing'})

What is the Rspec 3 way of doing this?

Rspec 3 这样做的方法是什么?

回答by Arup Rakshit

You should do

你应该做

allow(MyMod::Utils).to receive(:find_x).and_return({something: 'testing'})

Check out the doco Method stubs.

查看 doco方法存根