I'm currently playing around with Laravel HTTP Feature Tests and I noticed when executing this code below:
Test.php
$this->actingUser($user)
->withHeaders([..])
->post(uri: '/api/foo/bar', data: [..]);
the request()->path()
return /
in my routes/api.php
,
api.php
request()->path(); // returns '/' instead of '/foo/bar'.
but oddly enough, the request()
works well in any other files like my Controller
for example.
Has anybody faced this issue before?
I have properly imported Illuminate\Http\Request
and I have tried dd
the request()
itself, and it still comes out as empty.
It works exactly fine when I use Postman.
During a normal request, Laravel would be booted, which would involve route discovery and then route matching, which would include the routes files being loaded. At that point, the Request
object was created from an incoming HTTP request, so would match that.
Laravel feature tests don't actually make requests, they fake them. The framework has already been booted by the testing environment, so the routes files were already loaded, and Laravel creates a fake Request
for all CLI environments. At the point when your route files are loaded during testing, the fake request you're trying to create doesn't exist yet.