Sub topic 15
Running tests in scratch orgs
A scratch org is a short-lived Salesforce org that you create from a definition file. It starts empty, so each pipeline run tests your source in a clean environment. This chapter assumes you can already authenticate a workflow with an SFDX auth URL, and that you know the Apex test levels from earlier chapters.
Why test in a scratch org
A check-only deployment against a sandbox validates your change against that sandbox's current state. That state drifts. Someone adds a field by hand, a flow gets activated, or test data changes, and a test starts passing or failing for reasons unrelated to your pull request.
A scratch org removes that drift. Every run builds the org from two inputs: the definition file and your source. If the tests fail, the cause is in the repository.
Scratch orgs have costs too:
- They need a Dev Hub, which is an org with Dev Hub enabled that creates and tracks scratch orgs.
- Creation takes minutes, so the pipeline is slower than a check-only deploy.
- The Dev Hub enforces daily creation limits and a cap on active scratch orgs, and the limits depend on your edition.
- Your source must deploy cleanly into an empty org, which exposes undeclared dependencies.
The scratch org lifecycle in a pipeline
The pipeline creates the org, fills it, tests it, and always deletes it.
Authenticate to the Dev Hub, not to the scratch org
The pipeline never logs in to the scratch org. It logs in to the Dev Hub, and the CLI uses that connection to create the scratch org and store its credentials locally.
Save the Dev Hub auth URL as a secret. Use a name such as DEVHUB_AUTH_URL so it cannot be confused with a deployment target. Log in with --set-default-dev-hub so later commands find it:
sf org login sfdx-url \
--sfdx-url-file authurl.txt \
--alias devhub \
--set-default-dev-hubDefine the org shape
The definition file lives in config/project-scratch-def.json. It sets the edition, features, and settings of the new org.
{
"orgName": "CI scratch org",
"edition": "Developer",
"features": [],
"settings": {
"lightningExperienceSettings": {
"enableS1DesktopEnabled": true
}
}
}Add only the features and settings your code needs. If your Apex uses a feature the definition does not enable, such as Platform Cache or a specific license, the deploy or the tests fail in the scratch org even though they pass in production.
A complete workflow
This workflow runs on pull requests that touch source or configuration. It uses the run ID in the alias so two runs never share a name.
name: Scratch org tests
on:
pull_request:
branches: [main]
paths:
- 'force-app/**'
- 'config/**'
jobs:
scratch-tests:
runs-on: ubuntu-latest
timeout-minutes: 45
env:
SCRATCH_ALIAS: ci-${{ github.run_id }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Install Salesforce CLI
run: npm install --global @salesforce/cli
- name: Authenticate to the Dev Hub
env:
DEVHUB_AUTH_URL: ${{ secrets.DEVHUB_AUTH_URL }}
run: |
echo "$DEVHUB_AUTH_URL" > authurl.txt
sf org login sfdx-url --sfdx-url-file authurl.txt --alias devhub --set-default-dev-hub
rm authurl.txt
- name: Create scratch org
run: >
sf org create scratch
--definition-file config/project-scratch-def.json
--alias "$SCRATCH_ALIAS"
--duration-days 1
--target-dev-hub devhub
--wait 15
- name: Deploy source
run: sf project deploy start --source-dir force-app --target-org "$SCRATCH_ALIAS" --wait 30
- name: Run Apex tests
run: >
sf apex run test
--test-level RunLocalTests
--result-format junit
--code-coverage
--output-dir test-results
--wait 30
--target-org "$SCRATCH_ALIAS"
- name: Upload test results
if: always()
uses: actions/upload-artifact@v4
with:
name: apex-test-results
path: test-results
- name: Delete scratch org
if: always()
run: sf org delete scratch --target-org "$SCRATCH_ALIAS" --no-promptWhy each choice matters
--duration-days 1is a safety net. If the cleanup step never runs, the org expires on its own after one day.if: always()on the delete step makes it run after a failed test step. Without it, a failing run leaves an active scratch org that counts against your cap.if: always()on the upload step keeps the results available exactly when you need them for debugging.--output-dirwrites the result files. JUnit output is readable by many CI reporting tools.timeout-minutesstops a hung run from holding a scratch org for hours.
Prepare the org before testing
A freshly deployed scratch org is often not ready for tests. Add steps between deploy and test for whatever your tests assume:
- Install managed or unlocked packages first, before deploying source that depends on them.
- Assign permission sets with
sf org assign permset --name Your_Permission_Set --target-org "$SCRATCH_ALIAS". - Load reference data with
sf data import treeif your tests read records that are not created in the test itself.
Apex tests should create their own data, so the third step is rarely needed. Do it only when a test depends on data that tests cannot create.
Coverage in a scratch org
The 75 percent Apex coverage requirement is enforced when you deploy to production. A scratch org deploy does not enforce it. Your scratch pipeline can therefore pass while the production deploy fails on coverage.
To close that gap, read the coverage output from the test run and fail the job yourself when the percentage is too low. You can also keep the check-only deployment against the production-like target from the earlier chapter and use the scratch org for isolation, not coverage enforcement.
Common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Creation fails with a limit error | Daily or active scratch org cap reached in the Dev Hub | Delete leftover orgs, shorten durations, and make sure cleanup runs with `if: always()` |
| Deploy fails on a missing dependency | Package or feature not present in the empty org | Install the package first or add the feature to the definition file |
| Tests pass locally but fail in CI | Tests depend on org data or settings from your own org | Create data inside the test and declare settings in the definition file |
| Login step fails on pull requests from forks | GitHub does not pass secrets to workflows triggered by forks | Run the validation after a maintainer reviews the code, or require branches in the same repository |
| Run hangs at creation | Dev Hub is slow or unavailable | Raise `--wait` modestly and keep `timeout-minutes` as the upper bound |
When to choose scratch orgs
Use scratch orgs when your source is the single source of truth and you want reproducible tests. Prefer a sandbox check-only deploy when your org holds a lot of metadata that is not in the repository, or when run time and Dev Hub limits matter more than isolation. Many teams run both: scratch org tests on every pull request, and a check-only validation before merge to production.
Exercise
Your scratch org workflow fails at the Apex test step. A teammate later finds several active scratch orgs from failed runs in the Dev Hub, and new runs now fail at creation. What was missing from the workflow, and which two settings reduce the damage if cleanup still fails?
Show answer
The delete step needs if: always(), so it runs even when an earlier step fails. As backups, create the org with a short --duration-days (such as 1) so it expires on its own, and set timeout-minutes on the job so a hung run does not hold the org for long.
Exercise
A scratch org test run passes, but the production deployment of the same code fails with a coverage error. Why did the scratch org not catch it?
Show answer
Salesforce enforces the 75 percent Apex coverage requirement only on production deployments. A scratch org deploy and test run does not enforce it, so the job passed. Add your own check on the coverage output, or keep a validation against a production-like target.