Save WebDriver Test Reports or Screenshots To AWS S3

Save WebDriver Test Reports or Screenshots To AWS S3

AWS S3 is a useful way to share files with others. What’s cooler is getting your tests to automatically save files, like test reports or screenshots, to S3 once tests are done running.

Here’s how to do that using Ruby and Amazon Web Services’ Ruby API.

Install AWS Gems

First we need to import the aws-sdk-s3 gem file. You can install the complete AWS SDK, but if you only need to interact with a specific service, it’s better to install that specific gem. This is especially important when dealing with Docker and you want to keep your container as small as possible (Check out Build a Docker Image for Ruby, Watir Webdriver, Shopify API, Chrome, and Firefox).

So in this case, we’ll install and use the aws-sdk-s3 gem.

require 'aws-sdk-s3'

Set Your AWS Configuration

Next we need to set some connectivity and authentication details.

When hitting the AWS API, you need to specify your access key and your secret key. These are found in the Amazon console. Here’s some info on where to find them.

You also need to specify the AWS region your account is setup in.

Aws.config.update(
  {
    region: 'us-east-1',
    credentials: Aws::Credentials.new('AWS_ACCESS_KEY_GOES_HERE', 'AWS_SECRET_KEY_GOES_HERE')
  }
)

You can set the AWS configuration globally in this way, or you can also pass your AWS configuration directly when newing up your Resource, like so:

s3 = Aws::S3::Resource.new(region: 'us-east-1', credentials: Aws::Credentials.new('AWS_ACCESS_KEY_GOES_HERE', 'AWS_SECRET_KEY_GOES_HERE'))

Creating The S3 Resource Object

Next we need to create our S3 resource object. The resource object defines our S3 bucket.

Once created, we state the name of the bucket in which we want to save our item. We then can call the .object method to state the name of the item we want to save in the bucket.

Next we call the .upload_file method while specifying the name of the local file we want to save in S3.

s3 = Aws::S3::Resource.new
s3.bucket(bucketname).object(s3file).upload_file(localfile)

This will result in a copy of our localfile up in S3 with the name s3file.

Putting the whole thing in a method and wrapping the important bits in a rescue block, we have this:

require 'aws-sdk-s3'
# Saves a file to an AWS S3 bucket.
def store_file_in_s3
Aws.config.update({
region: 'us-east-1'
credentials: Aws::Credentials.new('AWS_ACCESS_KEY_GOES_HERE', 'AWS_SECRET_KEY_GOES_HERE')
})
bucketname = 'my_s3_bucket'
localfile = '/tmp/HelloWorld.txt'
s3file = 'HelloWorldS3File.txt'
s3 = Aws::S3::Resource.new
begin
s3.bucket(bucketname).object(s3file).upload_file(localfile)
rescue StandardError => e
puts 'Couldn\'t save file to S3. ' + e.message.to_s
end
end
view raw store_file_in_s3 hosted with ❤ by GitHub

 

Leave a Reply