Session lost during testing I have hit a brick wall with my testing. I have a helper method in app/helpers.php that accesses the authenticated user. However, during my tests this is always null. If I dd() the auth()->user() in the controller when doing the test I can see the value. But anything in blade or this helper file it always returns null. Even session()->all() is a completely empty array.
I do have SESSION_DRIVER=file in the .env.testing and phpunit.xml but no matter what it is still null.
Can you start by showing the test and maybe the controller method + helper function?
// TestController.php
class TestController extends Controller
{
public test()
{
dd(session()->all());
}
}
This then works as expected when doing get('/')->assertOk(). But in app/helpers.php I have.
// TestController.php
class TestController extends Controller
{
public test()
{
customer();
}
}
// app/helpers.php
function customer()
{
dd(session()->all());
}
This then is []. If I was to do auth()->user() in the controller I get the user when doing actingAs() but in the same helper method it becomes null.
@sam_bennett I just made the same set up and this gives me the user
function customer()
{
dd(auth()->user());
}
@Sinnbeck I am using PestPHP if that makes any difference?
@sam_bennett Same here. Did you try changing to auth()->user() instead of session()->all() ?
@Sinnbeck Yeah, I have tried it and others but it never seems to get the data.
@sam_bennett How are you loading your helpers.php ? This is mine
"autoload": {
"files": [
"app/helpers.php"
],
//etc
@sam_bennett Really strange. And it is the same test that uses() TestCase ?
@Sinnbeck Yeah, everything else is working fine but it's like the helper file doesn't have access to session
@sam_bennett That is really weird. A helper function is just a function. It shouldn't be anything special. I don't suppose it is on github publicly or you are able to make a minimal reproducible repo ?
What if you try the array session_driver? For testing that should be good enough.
@click I did have that originally and it was not working then, so I changed it to file to be the same as the normal .env but it made no difference.
@sam_bennett And if you output the name of the driver, is it the same for both of the cases (in the controller & in your method in helpers.php?
dd(session()->getDefaultDriver());
@click I get this "file" // app\helpers.php:397
@sam_bennett and I assume it is the same in the controller?
So the be 100% sure;
You call your controller via a unit test (via an api call)
public function test()
{
dump(session()->all());
dump(customer());
}
// app/helpers.php
function customer()
{
return session()->all();
}
This gives you one time a filled array and once an empty array?
If that is the case I only have one suggestion: "Did you try turning it off and on again" as it is a strange case.
Please sign in or create an account to participate in this conversation.