【问题标题】:How can I stub out a global function called from a constructor?如何存根从构造函数调用的全局函数?
【发布时间】:2019-04-11 18:55:26
【问题描述】:

我正在尝试存根从构造函数调用的全局函数。我正在使用 Rspec 和 Rspec-mocks。这是要测试的代码:

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:如果从另一个全局函数调用 fooexpect(self).to receive(:foo) { 'bar' } 将按预期工作。

【问题讨论】:

    标签: ruby rspec rspec-mocks


    【解决方案1】:

    最简单的解决方案可能是使用#allow_any_instance_of,因为“全局”函数实际上是Ruby 中的Kernel 方法。但是由于the documentation discourages 全球范围内的存根类,我想我至少会提供一个替代方案:

    def foo
      'foo'
    end
    
    class Bar
      def self.get_foo
        foo
      end
    
      def initialize
        @bar = self.class.get_foo
      end
    
      def bar
        @bar
      end
    end
    

    describe Bar do
      it 'gets foo' do
        expect(Bar).to receive(:get_foo).and_return('bar')
    
        expect(Bar.new.bar).to eq('bar')
      end
    end
    

    当然,如果可能的话,最好放弃Kernel方法,只使用类方法。

    【讨论】:

      【解决方案2】:
      allow_any_instance_of(Bar).to receive(:foo) { 'bar' }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-21
        • 2018-05-23
        • 2018-08-11
        • 1970-01-01
        • 2013-05-23
        • 1970-01-01
        • 1970-01-01
        • 2018-08-19
        相关资源
        最近更新 更多