Stubbing AWS S3 responses in Rails

Stubbing AWS S3 responses in Rails

Context

I was writing some test cases for a service object in which we have to generate and then upload a pdf to Aws S3 storage. Now this backend service is made using Rails 7 and i use rspec framework for writing my tests.

Now for S3 we use the aws-sdk-s3 gem. I wanted to stub the S3 response in my tests and for some reason i scoured the internet on how to make it work while rummaging throught the S3 docs to no avail.

Finally i found the sweetest and simplest solution so i decided to share it so it might save you some time. Just to keep things clear i will also share how my AWS config is setup incase you have some confusion regarding that.

AWS Setup in Rails

After installing the gem, my aws variables are defined in my application.yml file as i use figaro to keep them safe here is my aws_intializer file.

hash

The Magic

All you have to do is add

Aws.config[:s3] = { stub_responses: { put_object: true } }

in your test.rb file in your config/environment and it will take care of everything for you!