【问题标题】:How do you use Rspec any_instance stubbing of a Fog::Compute object?您如何使用 Fog::Compute 对象的 Rspec any_instance 存根?
【发布时间】:2014-06-26 06:28:03
【问题描述】:

尝试存根 Fog::Compute 对象的方法,如下所示:

describe EtHaproxy::Helpers do
  let(:helpers) { Object.new.extend(EtHaproxy::Helpers) }
  before do
    Fog.mock!
    Fog::Mock.reset

    @fog_conn = Fog::Compute.new(
      provider: 'AWS',
      aws_access_key_id: 'MOCK_ACCESS_KEY',
      aws_secret_access_key: 'MOCK_SECRET_KEY'
    )
    @fog_conn.data[:limits][:addresses] = 25
    2.times do
      @fog_conn.allocate_address('vpc')
    end

    @mock_eips = @fog_conn.addresses.map { |a| a.public_ip }

    Fog::Compute.any_instance.stub(:addresses).and_return(@fog_conn.addresses)
  end

  describe 'any_instance.stub' do
    it 'returns the specified value on any instance of the class' do
      o = Fog::Compute.new(
        provider: 'AWS',
        aws_access_key_id: 'MOCK_ACCESS_KEY',
        aws_secret_access_key: 'MOCK_SECRET_KEY'
      )
      o.addresses.should eq(@fog_conn.addresses)
    end
  end
end

但是,在运行此示例规范测试(从 the Relish docs for Rspec 2.14 提取)时,它失败了,说明:

Failure/Error: Fog::Compute.any_instance.stub(:foo).and_return(:return_value)
 NoMethodError:
   undefined method `any_instance' for Fog::Compute:Module

【问题讨论】:

    标签: ruby rspec stub fog


    【解决方案1】:

    事实证明,当使用Fog.Mock! 时,Fog 创建了一个便利层,而您实际上并没有处理Fog::Compute,而是我们最终得到了Fog::Compute::AWS::Mock。因此,要存根方法,我们需要这样做:

    Fog::Compute::AWS::Mock.any_instance.stub(:addresses).and_return(@fog_conn.addresses)
    

    在这个对象上存根会导致事情按预期工作。

    【讨论】:

      猜你喜欢
      • 2012-05-16
      • 2017-08-25
      • 2014-04-13
      • 2013-08-08
      • 1970-01-01
      • 2014-12-28
      • 2014-08-27
      • 2015-04-16
      • 2013-02-28
      相关资源
      最近更新 更多