Skip to content
shellhacks.dev
Testing

Run Bats Tests in a Directory with the bats Command

Run all .bats files in a folder with bats tests, and add -r to include subdirectories. Output is TAP when the output is not a terminal. Bats 1.8 and later.

1 min read
Summarize in AI

A project has several Bats test files, some of them in subfolders, and you want one command to run them all.

Shell
mkdir -p tests/sub
cat > tests/math.bats <<'EOF'
@test "addition" {
  [ "$((1 + 1))" -eq 2 ]
}

@test "false exits with 1" {
  run false
  [ "$status" -eq 1 ]
}
EOF
cat > tests/sub/nested.bats <<'EOF'
@test "nested test" {
  true
}
EOF
bats tests
echo "--- with -r"
bats -r tests
Text
1..2
ok 1 addition
ok 2 false exits with 1
--- with -r
1..3
ok 1 addition
ok 2 false exits with 1
ok 3 nested test

bats tests runs the .bats files directly inside the directory and does not enter subdirectories, so the first run reported 2 tests. With -r, bats recurses, and the nested file brought the total to 3. When the output goes to a pipe or file and not a terminal, the result is in TAP form, numbered tests with ok lines, which CI tools can read. See Usage in the Bats documentation.

A missing -r silently skips tests, which is easy to notice only when the count is lower than expected. Watch the plan line, 1..3, in CI. This run used Bats 1.8.2. Use --formatter pretty or --tap to pick the format explicitly, and --jobs to run tests in parallel when they are independent.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.