Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Response::download() test

I have the following code in one of my routes:

return Response::download('cv.pdf');

Any idea how to test this? I've tried to use shouldReceive() but that doesn't seem to work ('shouldReceive() undefined function....').

like image 592
sb89 Avatar asked Jan 13 '14 12:01

sb89


People also ask

How can user send response from Laravel explain methods to send data as response to browser?

Laravel provides several different ways to return response. Response can be sent either from route or from controller. The basic response that can be sent is simple string as shown in the below sample code. This string will be automatically converted to appropriate HTTP response.

What is test case in Laravel?

TestCase. php : The TestCase. php file is a bootstrap file for setting up the Laravel environment within our tests. This allows us to use Laravel facades in tests and provides the framework for the testing helpers, which we will look at shortly.

What is pest in Laravel?

Pest is a Testing Framework with a focus on simplicity. It was carefully crafted to bring the joy of testing to PHP. Get started. Source Code.


3 Answers

$response->assertDownload() was added in Laravel 8.45.0:

Assert that the response is a "download". Typically, this means the invoked route that returned the response returned a Response::download response, BinaryFileResponse, or Storage::download response:

$response->assertDownload();

Learn More:

https://laravel.com/docs/8.x/http-tests#assert-download

like image 194
Tanmay Avatar answered Oct 23 '22 19:10

Tanmay


EDIT: As pointed by @DavidBarker in his comment to the OP question

The Illuminate\Support\Facades\Response class doesn't actually extend Illuminate\Support\Facades\Facade so doesnt have the shouldRecieve() method. You need to test the response of this route after calling it in a test.


So if you want to test your download functionality, you can try checking the response for errors with:

$this->assertTrue(preg_match('/(error|notice)/i', $response) === false);
like image 35
Gadoma Avatar answered Oct 23 '22 18:10

Gadoma


You can assert that the status code is 200

$this->assertEquals($response->getStatusCode(), 200);

because sometimes you might have some data returned that match "error" or "notice" and that would be misleading.

I additionally assert that there's an attachment in the response headers:

$this->assertContains('attachment', (string)$response);
like image 39
Jad Joubran Avatar answered Oct 23 '22 18:10

Jad Joubran