• Reading time ~ 2 min
  • 11.02.2024

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());
// or
dd($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.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297