Andrew Wei
Andrew Wei

Reputation: 2080

How to Stub Responses with ruby Aws::Lambda::Client SDK

How do you mock lambda responses using the AWS ruby SDK ?

The documentation provided only gives basic usage examples for S3, which are not relevant for lambda requests.

https://docs.aws.amazon.com/sdkforruby/api/Aws/ClientStubs.html

Upvotes: 1

Views: 1024

Answers (1)

Andrew Wei
Andrew Wei

Reputation: 2080

By following the code of stub_responses, it brings you to convert_stub. There seems to be three viable options to mock the responses with: Proc, Hashand the else statement.

def convert_stub(operation_name, stub)
  case stub
  when Proc then stub
  when Exception, Class then { error: stub }
  when String then service_error_stub(stub)
  when Hash then http_response_stub(operation_name, stub)
  else { data: stub }
  end
end

source

In the mocking examples below, I have my AWS client setup as such.

aws_credentials = {
    region: 'us-east-1',
    access_key_id: Rails.application.secrets.aws_key,
    secret_access_key: Rails.application.secrets.aws_secret,
    stub_responses: Rails.env.test?
}
LAMBDA_CLIENT = Aws::Lambda::Client.new(aws_credentials)

Mocking Aws::Lambda::Types::InvocationResponse

The else statement allows you to essentially return the same object back. So the best way to mock the response, is to utilize the same class that is being used outside of the test environment. Aws::Lambda::Types::InvocationResponse

context do
  before do
    LAMBDA_CLIENT.stub_responses(
        :invoke,
        Aws::Lambda::Types::InvocationResponse.new(
            executed_version: "$LATEST",
            function_error: nil,
            log_result: nil,
            payload: StringIO.new("hello".to_json),
            status_code: 200
        )
    )
  end
  it { ... }
end

Mocking the HTTP Response

Following the logic of using a Hash, we need to peak into what http_response_stub does.

def http_response_stub(operation_name, data)
  if Hash === data && data.keys.sort == [:body, :headers, :status_code]
    { http: hash_to_http_resp(data) }
  else
    { http: data_to_http_resp(operation_name, data) }
  end
end

source

Evidently they are looking for a Hash with the following keys [:body, :headers, :status_code]

context do
  before do
    LAMBDA_CLIENT.stub_responses(
        :invoke,
        {
            body: {testing: true}.to_json,
            headers: {},
            status_code: 200
        }
    )
  end

  it { ... }
end

Upvotes: 2

Related Questions