Debug Methods Built Into Laravel’s TestResponse
Last updated on by Paul Redmond
Looking at Laravel’s HTTP Tests documentation carefully, you’ll notice some useful helpers built into the TestResponse
class to debug HTTP responses. This class recently had some internal updates to these methods in the way of the Laravel 11's Dumpable Trait, and I thought it would be a good time to revisit these useful helpers:
$response = $this->get('/'); $response->dump();$response->dumpHeaders();$response->dumpSession();
These methods have a dd()
counterpart too, which will “die and dump” response values:
$response->dd();$response->ddHeaders();$response->ddSession();
These methods are helpful shortcuts to just doing this yourself in a test:
dump($response->headers->all());// ordd($response->headers->all());
However, where these methods shine is when you modify an existing test that chains various assertions on the TestResponse
instance:
$this->postJson(route('post.store', $post)) ->assertSessionHasNoErrors() ->assertCreated() ->assertJson(['created' => true]);
Let’s say that assertSessionHasNoErrors()
fails, and I want to debug. I’ve noticed when I come across a chain that doesn’t assign the response, that I assign the response to a local variable like so:
$response = $this->postJson(route('post.store', $post)); dd($response); $response ->assertSessionHasNoErrors() ->assertCreated() ->assertJson(['created' => true]);
I will not argue whether you should chain assertions and never assign a local variable—that is more of a style preference—but you’ll come across situations where no local variable is assigned. Using these debug methods, we can quickly debug right before a test failure:
$this->postJson(route('post.store', $post))+ ->dumpSession() ->assertSessionHasNoErrors() ->assertCreated() ->assertJson(['created' => true]);
These debug helpers are handy when you want to debug the response somewhere between various assertions without grabbing the TestResponse
instance in a local variable.
Learn More
These features (and more) are covered in the Laravel documentation for HTTP Tests along with other useful TestResponse
features that make asserting JSON a breeze.