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:
- Enabling a developer to automatically capture screenshots of any new functionality on a branch or pull request;
- Quick and Dirty debugging - you can guarantee that if you’re out and about on a mobile device and don’t have your development environment to hand, there’s bound to be an emergency. Well now you can edit a file online in bitbucket, run the tests and view the resulting screenshots in Slack :)
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.
