How would you test code that uses the `old()` helper?

And why you might want to

Joel Clermont
Joel Clermont

As a rule, I try to never test Laravel framework code in my application tests. I trust that Laravel code is tested and I don't need to replicate that.

I was writing a test for a Blade component recently, and there was some value handling in the constructor I wanted to cover. This component was meant for user input, and you could specify a default value, but it would also fall back to old() form input if present.

There are a couple ways you could test this. One approach would be to set up the world where you have data in the session which the old() helper will look for. Then you could call your component, render it, and make assertions against the output.

But this involves a fair amount of setup since that session comes from the active request. And if I want to do a simple Blade component test, I don't even need a request.

Another approach would be to simply assert that the old() helper was called with the expected field name and default value fallback. The advantage here is there's nothing to set up and no request to generate.

I don't think there's one universally right answer here. Some of it boils down to a matter of taste and what else you might be doing in your test or component.

In my case, I chose the second approach. Which leads to the question: How do you do it?

The old() helper is on the Request, so you might start by mocking that Request class. I won't go into all the details here, but this is a bad idea, and will lead you down a difficult path.

Here's how I did it instead:


new MyBladeComponent('last_name');

    ->withArgs(['last_name', null]);

The spy doesn't try to mock out the Request class, it just monitors calls into its methods, enabling us to make assertions about them later.

With this test, I'm confident that my Blade component constructor was properly considering old form input, but I don't have to set up a bunch of session data to prove it.

Hope this helps,


P.S. Not writing tests in your app? Not sure where to start? We can help!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.