你如何使用Fog :: Compute对象的Rspec any_instance存根?

时间:2014-05-08 17:45:26

标签: ruby rspec stub fog

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

1 个答案:

答案 0 :(得分:4)

事实证明,当使用Fog.Mock!时,Fog会创建一个便利图层,而您实际上并未处理Fog::Compute,而是以Fog::Compute::AWS::Mock结尾。因此,要对方法进行存根,我们需要这样做:

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

对此对象进行存根会导致事情按预期运行。