Testing file deletions in Laravel Applications

Constantin Druc ยท 17 May, 2021

[00:00] We've seen how we can test file uploads and downloads but what about file deletions? How we can test that a file has been deleted? Well... let's go through it. I'll add a new test called destroy report and then, the first thing I'll do is to use the storage facade to fake the local disk. Next, we'll need an authenticated user and the report with an existing file we can delete.

[00:34] Then we'll make the request and assert that the report database entry has been removed and that its associated file has been deleted from the disk. Now let's go through these one by one. We can create a user using the user factory and then authenticate it with this acting as, to create a report we'll need a file and we can create one using the file class, create report.pdf, the file name, and then the size in kilobytes. And now that we have the file we can create a report, report, create, pass in a name, which will be sales, and to get the path we need to actually store the file. And we can do that with store, pass in the directory, and then the disk.

[01:48] Next up we need to send the request, and it will be a delete request, to route reports.destroy and we'll need to pass the report id as a parameter. Finally, we need to assert that the report is missing from the database: name sales, and that the associated file has been deleted - and we can do that with storage, disk, local, assert missing, and we need to pass the report path.

[02:38] Let's run the test and see what we get. So the reports destroy route is not defined. Let's add it. It will be very similar to this one, but we'll have delete instead of get, and destroy instead of show. So we'll call the destroy action on the reports controller. Let's add it: public function destroy, we'll receive the report via route model binding, we need to delete the report, and now to delete the file we can do storage, disk, local, delete, and we need to pass the path: report path.

[03:29] And if we run the test again it surely passes. Going through it one more time, we fake the local disk, we then create a user and authenticate it, then we create a report with an existing file, send the delete request, and finally we assert that the report is missing from the database and so does its associated file. And that's it that's how you test file deletions in Laravel applications.