Fdo
Fdo

Reputation: 1093

Stub response for AWS S3 Ruby SDK

I'm looking for a way to test my code that relies on AWS S3. I found the Advanced Client Stubbing tutorial but I was only able to find the correct way to stub list_objects from the Aws::S3::Client directly.

I don't want to refactor my code because I'm using the SDK with Aws::S3::Resource (a more OOP way):

s3_resource = Aws::S3::Resource.new(options)
objs = s3_resource.bucket(bucket_name).objects

The only way to successfully get the stubbed response I've been able to find so far is:

s3_client = Aws::S3::Client.new(stub_responses: true)
stubbed_objs = {
  contents: [
    { key: 'image.jpeg' },
    { key: 'test/image.jpeg' },
    { key: 'test/backup_2019-03-01T143129.sql.gz' },
    { key: 'test/backup_2019-04-01T143129.sql.gz' },
    { key: 'test/backup_2019-05-01T143129.sql.gz' },
    { key: 'test/image2.jpeg' },
    { key: 'backup_2019-06-01T143129.sql.gz' },
    { key: 'backup_2019-07-01T143129.sql.gz' },
    { key: 'backup_2019-08-01T143129.sql.gz' }
  ]
}
s3_client.stub_responses(:list_objects, stubbed_objs)
res = s3_client.list_objects({ bucket: "examplebucket" })

# Check the stubbed response
res.contents.map(&:key)
# => ["image.jpeg", "test/image.jpeg", "test/backup_2019-03-01T143129.sql.gz", "test/backup_2019-04-01T143129.sql.gz", "test/backup_2019-05-01T143129.sql.gz", "test/image2.jpeg", "backup_2019-06-01T143129.sql.gz", "backup_2019-07-01T143129.sql.gz", "backup_2019-08-01T143129.sql.gz"]

I've tried passing the Aws::S3::Client to the Aws::S3::Resource initializer, but I'm not getting the response objects from the stubs:

s3_client = Aws::S3::Client.new(stub_responses: true)

...

s3_resource = Aws::S3::Resource.new({ client: s3_client })
objs = s3_resource.bucket(bucket_name).objects
# => Returns 0 objects

I'm thinking s3_resource.bucket(bucket_name).objects makes multiple calls and that's why it's failing, or maybe the stubbed response format is different when using a Aws::S3::Resource vs direct Aws::S3::Client call.

Either way, any help with this is appreciated.

Upvotes: 1

Views: 2304

Answers (1)

Matthew  Lee
Matthew Lee

Reputation: 11

make a stub_responses using list_objects_v2, not list_objects it'll work

    s3_client = Aws::S3::Client.new(stub_responses: true)
    stubbed_objs = {
      contents: [
        { key: 'image.jpeg' },
        { key: 'test/image.jpeg' },
        { key: 'test/backup_2019-03-01T143129.sql.gz' },
        { key: 'test/backup_2019-04-01T143129.sql.gz' },
        { key: 'test/backup_2019-05-01T143129.sql.gz' },
        { key: 'test/image2.jpeg' },
        { key: 'backup_2019-06-01T143129.sql.gz' },
        { key: 'backup_2019-07-01T143129.sql.gz' },
        { key: 'backup_2019-08-01T143129.sql.gz' }
      ]
    }
    s3_client.stub_responses(:list_objects_v2, stubbed_objs)

Upvotes: 1

Related Questions