【问题标题】:rspec 3 - stub a class methodrspec 3 - 存根类方法
【发布时间】:2014-09-23 20:36:13
【问题描述】:

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

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

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

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

Rspec 3 的做法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby rspec rspec3


    【解决方案1】:

    你应该这样做

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

    查看文档Method stubs

    【讨论】:

    • 我正在尝试实现这一点,但是当我编写该模拟然后编写 expect(Class.foo).to eq(bar) 时,我收到“错误数量的参数错误”,因为 foo 方法通常需要 2 个参数... .但我只是希望它返回我放入存根中的内容
    • FWIW,这种形式会使我的 ruby​​ 解释器崩溃。但是,and_return 并不是严格需要的,可以省略。 (我的 ruby​​ 解释器也不会崩溃。)
    • @sixty4bit 你有什么理由不能用参数调用它吗?
    • @sixty4bit expect(Class.foo).to receive(bar).with(arg1, arg2).and_return({..object})
    猜你喜欢
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2019-12-27
    相关资源
    最近更新 更多