Everyday Rails

Using devcontainers in GitHub Actions CI workflows

By Aaron Sumner, January 14, 2024. File under: , , , .

I’m a big fan of GitHub Actions, especially the robust ecosystem of actions that can be included into continuous integration pipelines with just a few lines of configuration code. And thanks to the devcontainers/ci action, using an existing development container setup could make running a test suite or other common CI processes much, much simpler than it might have been in the past.

First off, this assumes you’ve already got your application set up to support devcontainer-based development, with a test suite that runs from within the container. If you don’t, this is as good a time as any to set one up.

Once that’s in place, create a file in .github/workflows to add the workflow. Name it something like ci.yml. Here’s what mine looks like:

name: CI

on:
  push:
    branches:
      - main
      - staging
  pull_request:
    branches:
      - main
      - staging

jobs:
  tests:
    name: Run test suite
    runs-on: ubuntu-latest

  steps:
    - name: Check out code
      uses: actions/checkout@v3

    - name: "Create environment files"
      run: |
        cp config/database-ci.yml config/database.yml
        cp .sample.env .env

    - name: run tests
      uses: devcontainers/ci@v0.3
      with:
        runCmd: bin/rspec --format documentation

Let’s break this down. I’ve set up the workflow to run any time a push is made to the main or staging branch, or a pull request is opened against either of those branches.

I’ve defined a job to run tests. The job is broken into three steps:

  • Check out the source code.
  • Copy necessary configuration files for CI to work. This may not be necessary for your application, or you may need to copy additional files.
  • Build the devcontainer, then use it to run my RSpec test suite.

That’s it! It may take some trial and error to work end-to-end. Approach it scientifically—change one thing, let it run, course-correct, and try again. When I’m creating a new GitHub Actions-based workflow, or updating an existing one, I usually create a draft pull request and make incremental changes to it, sneaking up gradually on the final solution.

Discussion

Follow along on on Mastodon, Facebook, or Bluesky to keep up-to-date with my latest posts. Better yet, subscribe to my newsletter for updates from Everyday Rails, book picks, and other thoughts and ideas that didn't quite fit here.
Buy Me A Coffee

Test with confidence!

If you liked my series on practical advice for adding reliable tests to your Rails apps, check out the expanded ebook version. Lots of additional, exclusive content and a complete sample Rails application.

Newsletter

Ruby on Rails news and tips, and other ideas and surprises from Aaron at Everyday Rails. Delivered to your inbox on no particular set schedule.