Quick Tip: Re-running Pest tests after file changes automatically
This is how you can rerun your tests hands free
I was just going through a ton of failed tests after a major refactor and I was spending a lot of time running the test, then fixing then running it again. Sure things like test runner plugins in VSCode/Zed/PHPStorm help in this area, but I wanted something portable.
That's when I came across entr - it's a small unix utility that allows you to pipe a list of files for it to watch and then pass a command to run when they do. Perfect! Here's what I ended up doing:
find app/ tests/ -type f | entr -r bash -c 'clear && php artisan test --retry --stop-on-defect'
So what all does that mean? Let me break it out:
find- the unix command for searching for things recursively based on the file attributesapp/ tests/- the directories I want to recursively watch| entr- piping all those recursively listed files to entr for watching-r bash -c- entr allows you to run an executable but in this case I want to run two commands "clear" and "php artisan" so I need to have the bash executable be an intermediary'clear && php artisan test- clear the screen and run the tests--retry- re-run the failed tests first--stop-on-defect- stop on the first test with an exception or other failure
That's it!
---
Bonus: if you remember Nuno demoing something like this awhile back (like I did) then you are correct! It did exist for a bit; sadly it has been removed in Pest v4 - https://pestphp.com/docs/upgrade-guide#content-watch--faker-plugin-deprecations