尝试存根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

最佳答案

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

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

在这个对象上执行stubing操作会产生预期的效果。

10-08 14:02