Let's talk about testing the file uploads and checking various things:
- Whether the file upload was successful
- Whether the file is where it belongs
- Whether the file name is assigned successfully.
Like a few other "external" things in Laravel, file uploads need to be faked for testing.
So, you don't work with the actual file uploads to the real storage. You fake the Storage driver, then Laravel, with its testing mechanism, puts those files elsewhere in a separate temporary folder, and then you assert whether that Storage temporary fake disk contains the file.
Scenario Example
For example, you have a Controller to store a product, and one of the fields is photo
. You store the photo in the products
folder and save the filename as a string to the photo
database field.
use App\Models\Product;use Illuminate\Http\Request;use Illuminate\Http\RedirectResponse; class ProductController extends Controller{ // ... public function store(Request $request): RedirectResponse { $product = Product::create($request->all()); if ($request->hasFile('photo')) { $filename = $request->file('photo')->getClientOriginalName(); $request->file('photo')->storeAs('products', $filename); $product->update(['photo' => $filename]); } return redirect()->route('products.index'); } // ...}
Test
The start of the test is...