Pete Pete - 1 year ago 59
Ruby Question

How do I mock AWS SDK (v2) with rspec?

I have a class which reads/processes messages from an SQS queue using the aws-sdk-rails gem (which is a wrapper on aws-sdk-ruby v2). How do I mock the AWS calls so I can test my code without hitting the external services?


class Communicator
def consume_messages
sqs_client =
# consume messages until the queue is empty
loop do
r = sqs_client.receive_message({
queue_url: "",
visibility_timeout: 1,
max_number_of_messages: 1
break if (response.message.length == 0)
# process r.messages.first.body
r = sqs_client.delete_message({
queue_url: "",
receipt_handle: r.messages.first.receipt_handle

Answer Source

I had a hard time finding examples mocking AWS resources. I spent a few days figuring it out and wanted to share my results on Stack Overflow for posterity. I used rspec-mocks (doubles & verifying doubles). Here's an example with the communicator.rb example in the question.


RSpec.describe Communicator do
  describe "#consume_messages" do
    it "can use rspec doubles & verifying doubles to mock AWS SDK calls" do
      sqs_client = instance_double(Aws::SQS::Client)
      allow(Aws::SQS::Client).to receive(:new).and_return(sqs_client)
      SQSResponse =
      SQSMessage =, :receipt_handle)
      response =['data/expected_body.json'), "receipt_handle")])
      empty_response =[])
      allow(sqs_client).to receive(:receive_message).
                            and_return(response, empty_response)
      allow(sqs_client).to receive(:delete_message).and_return(nil)