[英]In Laravel 8, how do I get the url of a request when unit testing?
I want to write a unit test in Laravel 8 to test a POST
request that creates a new entity.我想在 Laravel 8 中编写一个单元测试来测试一个创建新实体的
POST
请求。 In that request, a job_id
is created and the url has that job_id
appended.在该请求中,创建了一个
job_id
并且 url 附加了该job_id
。 I wish to retrieve that job_id
.我希望检索该
job_id
。 How do I do that?我怎么做?
For example,例如,
$route = route( 'job.store', $payload );
$response = $this->followingRedirects()->post( $route );
The $response
should redirect to something like http://localhost:9080/sales/job/J00561
. $response
应该重定向到类似http://localhost:9080/sales/job/J00561
。 I want to get the url so I can get job_id
, being J00561
.我想获取 url 以便我可以获取
job_id
,即J00561
。
How do I do that?我怎么做?
For this case, because it is not an API and you cannot get a created job ID from the response, I suggest the following:对于这种情况,因为它不是 API 并且您无法从响应中获取创建的作业 ID,我建议如下:
// create
$createResponse = $this->post(route('job.store', $payload))
->assertSuccessful();
// get created job by params
$job = Job::where($payload)->find();
// check creation
$this->assertNotNull($job);
// assert redirect
$createResponse->assertRedirect($showRoute = route('job.show', $jobId));
$this->get($showRoute)->assertSuccessful();
Here is another way: parse the header's Location
for jobId
, but in my opinion it's a wrong way:这是另一种方法:解析标题的
Location
为jobId
,但在我看来这是一种错误的方式:
$response = $this->post(route('job.store', $payload))
->assertSucceful();
$params = explode('/', parse_url($response->headers->get('Location'))['path']);
$jobId = array_pop($params);
$response->assertRedirect($showRoute = route('job.show', $jobId));
$this->get($showRoute)->assertSuccessful();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.