I want to write a unit test in Laravel 8 to test a POST
request that creates a new entity. In that request, a job_id
is created and the url has that job_id
appended. I wish to retrieve that 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
. I want to get the url so I can get job_id
, being 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:
// 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:
$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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.