Uploading RSpec screenshots to Slack

Uploading Ruby on Rails test suite screenshots from Bitbucket Pipelines to Slack

Most of our projects at Codeface have a Bitbucket Pipeline that performs tasks like running RSpec tests, spell-checking editorial content or checking the format of code with Rubocop.

There’s nothing like a nice green tick to reassure you that your latest changes haven’t introduced problems.

But sometimes those tests feel like they’re disappearing into a void - wouldn’t it be nice to get some screenshots as a visual confirmation that they’re actually running and everything is looking healthy?

Taking a screenshot from within an RSpec/Capybara test (or a Minitest/Capybara test) is as simple as save_screenshot.

Bitbucket doesn’t have a built-in way to view screenshots from test runs but since we’re already using Slack and have it open all day, we thought we’d have a go at automatically uploading screenshots to Slack after the automated tests have run.

We have this up and running on all our projects now. The screenshots go into their own channel in Slack so it’s not too intrusive.

As well as the ‘everyday’ screenshots for generally keeping an eye on things, it’s also great for:

Here’s a basic version of the script that we ended up with:

#!/usr/bin/env ruby
require 'slack-ruby-client'

Slack.configure do |config|
  config.token = ENV['SLACK_TOKEN']
end
client = Slack::Web::Client.new

SCREENSHOTS_DIR = './tmp/capybara'

if (File.directory? SCREENSHOTS_DIR)

  Dir.entries(SCREENSHOTS_DIR).each do |filename|
    next unless filename.end_with?('.png')

    full_path = File.join(SCREENSHOTS_DIR, filename)
    puts "Uploading to Slack: #{full_path}"

    response = client.files_upload_v2(
      filename: filename,
      content: File.read(full_path),
      channels: ['A0000A0000'],
      initial_comment: "Screenshot: #{full_path}",
      title: 'Bitbucket Pipelines Screenshots :camera:'
    )

  end

end

You can run this from an after-script in your pipeline with something like:

        after-script:
          - ruby ./bitbucket-upload-screenshots.rb $SLACK_TOKEN
          - exit $BITBUCKET_EXIT_CODE

You’ll need to put in a real channel ID, and have a secure pipeline environment variable for the Slack token.

The Pipeline has a machine which is spitting out flying screenshots, which make their way off to another cloud.  Are we in a cloud ourselves? Who knows...