Testing in CI
suggest changeContinuous integration (CI) runs your test suite automatically on every push and pull request, on a clean machine, so "works on my laptop" bugs are caught before they reach main. For a Ruby project, a good CI setup needs:
- one command that runs everything (
bundle exec rake) - a non-zero exit code when anything fails, because that is the only thing CI looks at
- reproducible runs: locked gem versions, a known Ruby version, a printed random seed
- fast feedback: cached gems, parallel jobs, cancelled outdated runs
This article builds that setup step by step with Minitest, RSpec and GitHub Actions, and shows the equivalent GitLab CI config at the end.
A single entry point: the Rakefile
CI configuration should be thin. Put the logic in a Rakefile so developers and CI run exactly the same thing. Minitest 5.16+ ships Minitest::TestTask:
# Rakefile
require "minitest/test_task"
Minitest::TestTask.create(:test) do |t|
t.libs << "test" << "lib"
t.test_globs = ["test/**/*_test.rb"]
t.warning = true # run with ruby -w
end
task default: :test
It defines a few useful tasks:
$ rake -T
rake test # Run the test suite
rake test:cmd # Print out the test command
rake test:isolated # Show which test files fail when run in isolation
rake test:slow # Run the test suite and report the slowest 25 tests
A small project to test:
# lib/price.rb
module Price
module_function
def with_tax(amount, rate: 0.23)
raise ArgumentError, "negative amount" if amount.negative?
(amount * (1 + rate)).round(2)
end
end
# test/test_helper.rb
$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require "minitest/autorun"
# test/price_test.rb
require_relative "test_helper"
require "price"
class PriceTest < Minitest::Test
def test_adds_default_tax
assert_equal 123.0, Price.with_tax(100)
end
def test_custom_rate
assert_equal 108.0, Price.with_tax(100, rate: 0.08)
end
def test_rejects_negative
assert_raises(ArgumentError) { Price.with_tax(-1) }
end
end
$ rake
Run options: --seed 34873
# Running:
...
Finished in 0.001578s, 1900.7817 runs/s, 1900.7817 assertions/s.
3 runs, 3 assertions, 0 failures, 0 errors, 0 skips
If you use RSpec, the equivalent is:
# Rakefile
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec)
task default: :spec
Add more checks to the default task as the project grows, e.g. task default: %i[test rubocop] with require "rubocop/rake_task"; RuboCop::RakeTask.new.
Exit codes are what CI sees
CI runners don't read your output; they look at the exit status of each step. A failing test makes rake exit with status 1:
$ rake; echo "exit=$?"
Run options: --seed 36871
# Running:
F..
Finished in 0.001902s, 1576.8725 runs/s, 1576.8725 assertions/s.
1) Failure:
PriceTest#test_adds_default_tax [test/price_test.rb:6]:
Expected: 124.0
Actual: 123.0
3 runs, 3 assertions, 1 failures, 0 errors, 0 skips
rake aborted!
Command failed with status (1): [ruby -Ilib:test:.:test:lib -w -e 'require "minitest/autorun"; require "test/price_test.rb"' -- ]
exit=1
Watch out for things that swallow the exit code: rake test || true, piping into another command (rake | tee log.txt returns tee's status unless the shell runs with set -o pipefail; GitHub Actions enables it only when a step explicitly says shell: bash), or custom scripts that rescue Exception and keep going. In your own scripts use exit 1 or abort "message" on failure.
GitHub Actions workflow
Create .github/workflows/ci.yml:
name: CI
on:
push:
branches: [main]
pull_request:
# Cancel an older run of the same branch/PR when a new commit is pushed
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 15
env:
CI: true
steps:
- uses: actions/checkout@v5
- uses: ruby/setup-ruby@v1
with:
ruby-version: "4.0"
bundler-cache: true # runs bundle install and caches gems
- run: bundle exec rake
ruby/setup-ruby is the official action maintained by the Ruby core team. With bundler-cache: true it runs bundle install and caches the installed gems keyed on Gemfile.lock, so a typical second run installs gems in seconds instead of minutes.
If you omit ruby-version, it reads .ruby-version (or .tool-versions, or mise.toml) from the repository. That is the best choice for applications: the local and CI versions can never drift apart.
timeout-minutes matters more than it looks: the default job timeout is 6 hours, and a test stuck waiting on a socket will happily burn all of it.
Commit Gemfile.lock and add the CI platform
Applications should commit Gemfile.lock, so CI installs exactly the versions you tested locally. If you develop on macOS or Windows, Bundler may have locked only your platform; add Linux so CI doesn't have to re-resolve:
$ bundle lock --add-platform x86_64-linux
bundler-cache: true also runs Bundler in deployment mode (frozen), so a Gemfile change without an updated Gemfile.lock fails the build instead of silently resolving new versions.
Testing multiple Ruby versions
Gems should be tested against every Ruby version they support. Use a matrix:
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
ruby: ["3.3", "3.4", "4.0"]
include:
- os: macos-latest
ruby: "4.0"
- os: windows-latest
ruby: "4.0"
steps:
- uses: actions/checkout@v5
- uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true
- run: bundle exec rake
ruby-head:
runs-on: ubuntu-latest
continue-on-error: true # don't block merges on unreleased Ruby
steps:
- uses: actions/checkout@v5
- uses: ruby/setup-ruby@v1
with:
ruby-version: head
bundler-cache: true
- run: bundle exec rake
Two gotchas:
- Always quote versions. In YAML
3.0is the float3, which setup-ruby interprets as "latest 3.x". Write"3.0". fail-fast: falselets all matrix jobs finish, so you see whether a failure is specific to one Ruby version or universal.
Gems usually do not commit Gemfile.lock (or CI ignores it), so they get tested against the newest compatible dependencies, which is what users will install.
Databases and other services
Integration tests often need PostgreSQL, MySQL or Redis. GitHub Actions can start them as service containers next to your job:
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:17
env:
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
POSTGRES_DB: app_test
ports: ["5432:5432"]
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 10
redis:
image: redis:7
ports: ["6379:6379"]
env:
CI: true
DATABASE_URL: postgres://app:secret@localhost:5432/app_test
REDIS_URL: redis://localhost:6379/0
steps:
- uses: actions/checkout@v5
- uses: ruby/setup-ruby@v1
with:
bundler-cache: true
- run: bin/rails db:schema:load
- run: bin/rails test
The --health-cmd options make the runner wait until Postgres accepts connections before your steps start. Read connection settings from environment variables in your code (ENV.fetch("DATABASE_URL")) rather than hard-coding them, so the same code works locally, in CI and in production.
Random order and reproducing failures
Minitest always runs tests in random order and prints the seed (Run options: --seed 34873). This exposes tests that depend on each other through shared state. When CI fails but your machine passes, re-run with CI's seed:
$ SEED=34873 rake test
$ rake test A="--seed 34873 -v" # same thing, verbose
Run just one test, by name or regexp (Minitest 6 uses -i; Minitest 5 used -n):
$ SEED=42 rake test A="-v -i /negative/"
Run options: -v -i /negative/ --seed 42
# Running:
PriceTest#test_rejects_negative = 0.00 s = .
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
If a test fails only in combination with others, let the tool find the minimal set:
$ rake test A="--bisect --seed 34873" # Minitest
$ bundle exec rspec --bisect --seed 34873
RSpec runs in defined order by default; turn on random order in spec/spec_helper.rb:
RSpec.configure do |config|
config.order = :random
Kernel.srand config.seed # make rand/shuffle in tests follow the seed too
# A forgotten `fit` / `focus: true` would silently skip the rest of the suite
config.filter_run_when_matching :focus
config.before(:example, :focus) { raise "Focused spec committed: remove :focus" } if ENV["CI"]
end
Most CI services (GitHub Actions, GitLab, CircleCI, Buildkite) set CI=true, which makes ENV["CI"] a convenient switch for stricter, CI-only checks like the one above.
Making CI stricter than local runs
A few checks are annoying locally but valuable in CI.
Treat Ruby warnings as errors. Warnings like "method redefined" or deprecations are early signs of bugs and upcoming breakage. With t.warning = true in the Rakefile, Ruby prints them; in CI you can make them fatal:
# test/test_helper.rb
if ENV["CI"]
module Warning
def self.warn(message, category: nil)
raise "Ruby warning treated as error: #{message}"
end
end
end
Putting that override and some sloppy code in one file, warn.rb:
# ... the `if ENV["CI"]` block above (lines 1-7) ...
def greet = puts("hi")
def greet = puts("hello") # warning: method redefined
$ CI=true ruby -w warn.rb
warn.rb:4:in 'Warning.warn': Ruby warning treated as error: warn.rb:10: warning: method redefined; discarding old greet (RuntimeError)
warn.rb:9: warning: previous definition of greet was here
from warn.rb:10:in '<main>'
Gems you depend on may emit warnings you can't fix; in that case filter by path (return super unless message.include?(Dir.pwd)) instead of raising on everything.
Run linters and a security audit as separate jobs, so a style issue doesn't hide test results:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: ruby/setup-ruby@v1
with:
bundler-cache: true
- run: bundle exec rubocop --format github
- run: bundle exec bundle-audit check --update
rubocop --format github prints offenses as GitHub annotations, which appear inline on the pull request diff. bundle-audit (from the bundler-audit gem) checks Gemfile.lock against the Ruby security advisory database.
Showing test failures on the pull request
GitHub turns lines like ::error file=x.rb,line=3::message printed by any step into annotations on the diff. A tiny Minitest reporter can emit them for failing tests:
# test/test_helper.rb
if ENV["GITHUB_ACTIONS"] == "true"
class GithubAnnotations < Minitest::AbstractReporter
def initialize
super
@failures = []
end
def record(result)
@failures << result unless result.passed? || result.skipped?
end
# Called once at the end; workflow commands must start at the beginning of a line
def report
@failures.each do |r|
file, _, line = r.failure.location.rpartition(":")
file = file.delete_prefix("#{Dir.pwd}/")
msg = r.failure.message.lines.first.chomp
puts "::error file=#{file},line=#{line},title=#{r.class_name}##{r.name}::#{msg}"
end
end
end
module Minitest
def self.plugin_github_annotations_init(_options)
reporter << GithubAnnotations.new
end
end
Minitest.extensions << "github_annotations"
end
Output after the normal summary:
3 runs, 3 assertions, 1 failures, 0 errors, 0 skips
::error file=test/price_test.rb,line=6,title=PriceTest#test_adds_default_tax::Expected: 124.0
Minitest calls plugin_<name>_init for every name in Minitest.extensions, which is how real plugin gems hook in.
JUnit XML reports
Many CI systems (GitLab, Jenkins, CircleCI, Buildkite, and GitHub via third-party actions) understand JUnit XML and show per-test results, timings and flaky-test history. Ruby formatters:
# Gemfile
group :test do
gem "minitest-reporters" # Minitest
gem "rspec_junit_formatter" # RSpec
end
# test/test_helper.rb (Minitest)
require "minitest/reporters"
reporters = [Minitest::Reporters::ProgressReporter.new]
reporters << Minitest::Reporters::JUnitReporter.new("tmp/test-results") if ENV["CI"]
Minitest::Reporters.use!(reporters)
# RSpec: keep human-readable output and also write XML
$ bundle exec rspec --format progress --format RspecJunitFormatter --out tmp/rspec.xml
Upload the reports (and anything else useful for debugging, like logs or screenshots from system tests) even when the tests fail:
- run: bundle exec rake
- uses: actions/upload-artifact@v4
if: failure() || success()
with:
name: test-results-${{ matrix.ruby }}
path: tmp/test-results/
Speeding up a slow suite
First find out where the time goes:
$ rake test:slow # Minitest: 25 slowest tests
$ bundle exec rspec --profile 10 # RSpec: 10 slowest examples
Parallelize inside one job. Minitest can run test classes in threads with parallelize_me!; Rails runs tests in processes with parallelize(workers: :number_of_processors) in test/test_helper.rb, giving each worker its own database. Only do this for tests that don't share global state.
Split across jobs. For large suites, run slices of the test files on separate CI machines. A deterministic split needs no external service:
# bin/ci-split: print the test files this CI node should run
index = Integer(ENV.fetch("CI_NODE_INDEX", "0"))
total = Integer(ENV.fetch("CI_NODE_TOTAL", "1"))
files = Dir["test/**/*_test.rb"].sort
mine = files.each_with_index.select { |_, i| i % total == index }.map(&:first)
puts mine
$ CI_NODE_INDEX=0 CI_NODE_TOTAL=2 ruby bin/ci-split
test/a_test.rb
test/c_test.rb
test/e_test.rb
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node: [0, 1, 2, 3]
env:
CI_NODE_INDEX: ${{ matrix.node }}
CI_NODE_TOTAL: 4
steps:
- uses: actions/checkout@v5
- uses: ruby/setup-ruby@v1
with:
bundler-cache: true
- run: >-
bundle exec ruby -Ilib -Itest
-e 'ARGV.shift(ARGV.size).each { require File.expand_path(it) }'
$(ruby bin/ci-split)
The -e script requires each file and empties ARGV so Minitest doesn't try to parse file names as options. For RSpec it's simpler: bundle exec rspec $(ruby bin/ci-split) with the glob changed to spec/**/*_spec.rb. Splitting by file count is crude; gems like knapsack or parallel_tests balance slices using recorded timings.
Cache more than gems. bundler-cache handles gems. For Rails apps, also cache node_modules or precompiled assets with actions/cache, and use bootsnap to speed up boot.
GitLab CI equivalent
# .gitlab-ci.yml
image: ruby:4.0
variables:
BUNDLE_PATH: vendor/bundle
BUNDLE_FROZEN: "true"
cache:
key:
files: [Gemfile.lock]
paths: [vendor/bundle]
test:
services:
- postgres:17
variables:
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
POSTGRES_DB: app_test
DATABASE_URL: postgres://app:secret@postgres:5432/app_test
script:
- bundle install --jobs 4
- bundle exec rake
artifacts:
when: always
reports:
junit: tmp/test-results/*.xml
The structure is the same: a fixed Ruby image, a gem cache keyed on Gemfile.lock, services, bundle exec rake, and JUnit reports that GitLab shows on the merge request. Note that services are reachable by their image name (postgres), not localhost.
Tips
- Keep the CI file thin; anything you can't run locally with one command will rot.
- Make the build red for real problems only. A flaky test that fails 1 in 20 runs teaches everyone to click "re-run"; fix it or delete it, and use the printed seed plus
--bisectto find order dependencies. - Pin what matters: Ruby version (
.ruby-version), gems (Gemfile.lock), service images (postgres:17, notpostgres:latest). - Don't let tests talk to real external services in CI; stub HTTP with
webmockor record it withvcr, and setWebMock.disable_net_connect!(allow_localhost: true). - Never print secrets. Pass them via the CI's secret store (
${{ secrets.API_KEY }}), and remember that pull requests from forks don't receive secrets. - Measure coverage in CI with SimpleCov and fail below a threshold; see Code coverage.