The Problem
Sometimes, when running integration tests using Laravel and PHPUnit, it’s useful to inspect the response when you can’t figure out why the test is failing. In Laravel 5 and later versions, testing has been highly improved with an API that allows nice and fluent interaction with your application.
Inspect the Response Object
In Laravel, each Test extends the default abstract TestCase
class defined in Illuminate\Foundation\Testing
. This class uses the CrawlerTrait
to provide iteraction with the application, therefore it contains the $response
property, which is an instance of \Illuminate\Http\Response
and contains the last response returned by the application.
For this reason we can use the getContent()
method on the response object to check what the application actually returned. In the following example we are first creating a new user in the database, then we use the chainable API to interact with the application. Finally we use the dd
function to dump the variable and stop the execution of the script:
<?php
/** @test */
public function user_can_successfully_login()
{
$user = factory(App\User::class)->create([ 'password' => 'password' ]);
$this->visit('/login')
->type($user->email, 'email')
->type('password', 'password')
->press('submit')
->seePageIs('/');
dd($this->response->getContent());
}
If you look carefully, the CrawlerTrait
offers a nice shortcut to achieve the same result, so instead of dd($this->response->getContent())
you can simply use $this->dump()
.
For the curious out there, here is its implementation:
<?php
public function dump()
{
$content = $this->response->getContent();
$json = json_decode($content);
if (json_last_error() === JSON_ERROR_NONE) {
$content = $json;
}
dd($content);
}
Update (10 November 2018)
The dump()
function has been removed from the TestCase
class since Laravel 5.4, but you can use the one provided by the TestResponse
class. (See Api Reference)
Inspect the Session Object
On the other hand, if you want to inspect the Session
object after a response, for example if you are looking for validation errors, you can use the following instruction:
<?php
dd($this->app['session.store']);