Laravel Tip: Desktop notifications from your tests
Peter Fox
Posted on May 20, 2020
If you didn’t know, Laravel now has a php artisan test command which comes from the nunomaduro/collision package which is used to display beautiful and easy to diagnose errors from the artisan command like so:
This package is created and maintained by Nuno Maduro among many other useful packages and tools like PHP Insights, Laravel Mojito and the upcoming PestPHP testing tool.
Hooking into command events
Two events are fired for every artisan command execution, one before the console command starts and another after the command finishes. We can write a listener for this but to keep this simple we’ll use a callable instead and add it to the boot method in our AppServiceProvider. By hooking into the command finished event we can also see what the exit code for the command was. In the case of the test command we know that an exit code of 0 means our tests passed and a exit code of 1 or higher is the tests failing.
Building our desktop notification
So I mentioned Nuno Maduro earlier and that wasn’t a coincidence because another package of his is what we’ll use to display our desktop notification.
composer require --dev nunomaduro/laravel-desktop-notifier
Once the package is install we now add a method to the AppServiceProvider so that a desktop notification is delivered to the operating system.
Our method is fairly straightforward and just changes the text of the notification based on the true/false result of our tests.
After that we can bring is all together in the AppServiceProvider and run the tests command.
Now when we run the php artisan test command we’ll get a notification telling us when they’re completed and if they’ve passed or failed.
Conclusion
Well there’s not much more to say here. There’s some really simple things you can do to expand your application and make your life easier. You can effectively tap into the exit code of and command in your application. You can also tap into the start of a command as well which is very useful. For instance, I’ve created a listener that cleans out the testing logs everytime the tests are about to run making it easier to see what was generated without the clutter of the extra test
If you want to see this demo in action you can clone it from github.
I’m Peter Fox, a software developer in the UK who works with Laravel among other things. Thank you for reading my articles. I’ve got several more on both medium and dev.to that. If you want to know more about me you can at https://www.peterfox.me and feel free to follow me @SlyFireFox on twitter for more Laravel tips and tutorials in the future.
Posted on May 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.