How to run setup and teardown once per collection run in API Spector
Some setup belongs to the whole run, not to each request: sign in once, seed a record, clear a token left over from last time, and tidy up at the end. In API Spector you do that with lifecycle hooks on a collection.
Mark a request as a hook
Right click any request in the sidebar and open the hook menu. You can tag it as Before All, Before, After, or After All, and the request shows a small badge for its role.
- Before All and After All run once, around the entire run of their scope.
- Before and After run around every request in the scope.
A hook tagged at the top of a collection applies to the whole collection run. A hook inside a folder applies once per folder run.
Put your setup in the hook's script
A hook is a normal request, so it has its own Pre request and Post response script tabs, and that is where setup and teardown go. For example, a Before All request can clear a value left from a previous run:
sp.environment.clear('accessToken');
A Before All request can also call your login endpoint and store a token the rest of the run reuses, by saving a field from the response in its post response script:
sp.environment.set('accessToken', sp.response.json().token);
An After All request is the place to undo things: delete the record you created, or clear the token so the next run starts clean.
How failures behave
The ordering is predictable. A Before All that fails stops its scope, because the setup it was meant to guarantee is not there. A Before that fails skips its one request. After and After All still run, so cleanup happens even when something earlier failed.
It runs the same from the CLI
The run plan is the same whether you run the collection from the app's Runner or from the command line in CI, so the once per run setup and teardown you define applies to both.
Why it helps
Without run level hooks, people copy the same login step into every request or reset state by hand between runs. One Before All and one After All replace all of that, and because they are ordinary requests with scripts, there is nothing new to learn.