Trying to stub a method of a Fog::Compute
object, like so:
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
However, upon running this example spec test (lifted from the Relish docs for Rspec 2.14), it fails, stating:
Failure/Error: Fog::Compute.any_instance.stub(:foo).and_return(:return_value)
NoMethodError:
undefined method `any_instance' for Fog::Compute:Module
As it turns out, when using Fog.Mock!
, Fog creates a convenience layer, and you’re not actually dealing with Fog::Compute
, but instead, we end up with Fog::Compute::AWS::Mock
. As such, to stub the method, we need to do it like so:
Fog::Compute::AWS::Mock.any_instance.stub(:addresses).and_return(@fog_conn.addresses)
Stubbing on this object results in things working as expected.