Ruby 如何将从构造函数调用的全局函数存根出来?

Ruby 如何将从构造函数调用的全局函数存根出来?,ruby,rspec,rspec-mocks,Ruby,Rspec,Rspec Mocks,我正在尝试删除一个从构造函数调用的全局函数。我正在使用Rspec和Rspec mock。下面是要测试的代码: def foo 'foo' end class Bar def initialize @bar = foo end def bar @bar end end 下面是测试: describe 'bar' it 'calls foo' do expect(self).to receive(:foo) { 'bar' } expe

我正在尝试删除一个从构造函数调用的全局函数。我正在使用Rspec和Rspec mock。下面是要测试的代码:

def foo
  'foo'
end

class Bar
  def initialize
    @bar = foo
  end

  def bar
    @bar
  end
end
下面是测试:

describe 'bar'
  it 'calls foo' do
    expect(self).to receive(:foo) { 'bar' }

    expect(Bar.new.bar).to eq('bar')
  end
end
测试失败,并显示以下消息:

     Failure/Error: expect(Bar.new.bar).to eq('bar')

       expected: "bar"
            got: "foo"

       (compared using ==)
如何删除全局函数foo


PS:expectself.to receive:foo{'bar'}在从另一个全局函数调用foo时按预期工作。

最简单的解决方案可能是使用allow_any_instance_of,这很有效,因为全局函数实际上是Ruby中的内核方法。但是,由于在全球范围内存根类,我认为我至少应该提供一个替代方案:

allow_any_instance_of(Bar).to receive(:foo) { 'bar' }
德福 “福” 终止 分类栏 def self.get_foo 福 终止 def初始化 @bar=self.class.get\u foo 终止 def棒 @酒吧 终止 终止 及

描述一下吧 它“变得很有趣” expectBar.to receive:获取\u foo.并返回'bar' expectBar.new.bar.至eq'bar' 终止 终止 当然,如果可能的话,最好不要使用内核方法,而只使用类方法