Exit Build Early if Any Test Fails

Cancel On Test Fail Using API

You may have specific builds that you want to exit/fail as soon as any test fails, especially if you are splitting the tests across many containers.

You can accomplish this by adding the following step after your test run step:

- run:
    name: Fail Fast
    when: on_fail
    command: |
      echo "Canceling workflow as a step resulted in failure"
      curl -X POST --header "Content-Type: application/json" "https://circleci.com/api/v2/workflow/${CIRCLE_WORKFLOW_ID}/cancel?circle-token=${CIRCLE_TOKEN}" 

The above also requires that you generate a Personal API token and store it as CIRCLE_TOKEN as a project level environment variable.

What the above does is when a build moves to a 'failed' state (such as when a test fails), it sends an API call to the workflows endpoint to cancel the entire workflow.

Some notes about the above solution:

  1. It will cancel the workflow instead of moving it to a "Failed" state
  2. This command will run on any failure of a job step, not just a test failure

Additional Resources

Was this article helpful?
3 out of 14 found this helpful



Article is closed for comments.