最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Laravel HTTP Tests Routing Issue - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Feb 4 at 11:55 matiaslauriti 8,1024 gold badges36 silver badges47 bronze badges asked Feb 4 at 9:10 afkkaafkka 32 bronze badges 2
  • check content of request()->path() inside bound to route controller, not in routes/api.php. My guess that you accessing real version of Request, instead of mocked from test. – Tymur Valiiev Commented Feb 4 at 9:47
  • You have to show a real test, as I have no idea where you are using request() in your api.php, and for sure you are doing something wrong, so having all the information would help us help you – matiaslauriti Commented Feb 4 at 11:57
Add a comment  | 

1 Answer 1

Reset to default 1

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.

发布评论

评论列表(0)

  1. 暂无评论