Laravel 11.34: Refining Your Testing Workflow and String Helpers
Overview
Prerequisites
To follow this guide, you should have a baseline understanding of the Storage, Http, and Number is essential.
Key Libraries & Tools
- Laravel 11.34: The core framework providing these new helpers.
- Storage Facade: Handles filesystem abstractions and mocking.
- HTTP Facade: Manages outgoing API requests with powerful testing fakes.
- Number Helper: A utility class for formatting and manipulating numeric data.
Code Walkthrough
1. Simplified Storage Assertions
Testing file uploads or generated reports becomes faster with the assertCount method. Instead of manually retrieving all files and counting them, you can now verify the state of a disk directly.
Storage::fake('photos');
// ... perform logic that saves 3 files ...
Storage::disk('photos')->assertCount(3);
2. HTTP Fake Shorthands
Previously, faking an Http::response(). Laravel now infers the response type based on the value you provide in the fake array.
Http::fake([
'api.example.com/*' => ['title' => 'My Fake Podcast'], // Auto-resolves to 200 JSON
'api.example.com/error' => 500, // Auto-resolves to status code
'api.example.com/text' => 'Plain text response', // Auto-resolves to string
]);
3. Ordinal Spelling
The Number helper now includes a spellOrdinal method. This combines the logic of converting a number to its ordinal form (1st, 2nd, 3rd) and spelling it out as text.
use Illuminate\Support\Number;
// Returns "forty-seventh"
$result = Number::spellOrdinal(47);
Syntax Notes
Laravel uses Type Inference within the Http::fake() method. If the value is an array, it assumes a JSON response with a 200 status. If it's an int, it treats it as the status code. This removes the need for repetitive
Practical Examples
- Leaderboards: Use
Number::spellOrdinalto display "You finished in twenty-first place" in a user-friendly UI. - Data Pipelines: Use
Storage::assertCountto ensure a batch process generated exactly the expected number of CSV segments. - API Integration: Quickly mock external services by returning raw arrays in your test setup, keeping the "Arrange" section of your tests concise.
Tips & Gotchas
When using the HTTP shorthands, remember that returning an int will result in an empty response body with that status code. If you need a specific body and a non-200 status code, you must still use the full Http::response($body, $status) syntax to avoid ambiguity.
