logo
podcast Podcast
get help Get Unstuck

Should all request data in tests be strings?

Tests should act like the real world

Joel Clermont
Joel Clermont
2024-07-31

Any time a bug slips past a passing test suite, it always makes me pause and consider what I could have done differently.

On a recent Laravel project upgrade, we bumped the laravel-permisisons package from v5 to v6. In the changelog, it calls out some changes around passing in role IDs as strings instead of numbers.

To be honest, I read it, but I didn't give it much consideration. Plus, all my tests passed as expected.

But shortly after deploying the upgrade, I was getting an error on the user management page like this:

There is no role named 4 for guard web.

Now that comment in the changelog made sense to me. When you have an HTML form that lets you set roles, and it passes in the IDs, those IDs are always strings.

Why? Because ALL form data is sent as strings.

Now, back to the testing question: In my test, I was setting something like 'roles' => [1, 2, 3] in the request payload, so my tests were passing.

This leads me to my original question: Should all form data in tests be set as strings?

I think the answer is yes. If that's how the data is coming in on a real request, my tests should match that behavior.

Obviously, if it's a JSON request, that's a separate matter, but for HTML form data, I think it's safest to always pass in strings.

Here to help,

Joel

P.S. Beyond Code makes some very useful tools for Laravel developers. And if you purchase with our link, they help support this site.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.