Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hjortur17's avatar

Session is missing expected key [errors]. Failed asserting that false is true.

Hi, I can't figure out how to get this to green. I get this error message when running this method

ERROR:

Session is missing expected key [errors].
Failed asserting that false is true.

METHOD:

/** @test */
    public function a_reply_requires_a_body()
    {
        $this->withExceptionHandling()->signIn();

        $thread = create('App\Thread');
        $reply = make('App\Reply', ['body' => null]);

        $this->post($thread->path().'/athugasemdir', $reply->toArray())
            ->assertSessionHasErrors('body');
    }
0 likes
21 replies
mushood's avatar

Be sure to have Session::start() at the beginning of your test. You can also place this in your setup function if you are using it several places.

1 like
mushood's avatar

Can you post your controller code as well?

1 like
hjortur17's avatar

@MUSHOOD - Here you go:

public function store($channelId, Thread $thread)
{
    try {
        request()->validate(['body' => 'required|spamfree']);

        $reply = $thread->addReply([
            'body' => request('body'),
            'user_id' => auth()->id()
        ]);
    } catch (\Exception $e) {
        return response('Sorry, your reply could not be saved at this time', 422);  
    }

    return $reply->load('owner');
}
1 like
mushood's avatar

@h The validation exception is being caught in your catch and you are returning only this response

return response('Sorry, your reply could not be saved at this time', 422);  

Comment out the try catch block and see if it works

mushood's avatar

Like this

   // try {
        request()->validate(['body' => 'required|spamfree']);

        $reply = $thread->addReply([
            'body' => request('body'),
            'user_id' => auth()->id()
        ]);
  //  } catch (\Exception $e) {
   //     return response('Sorry, your reply could not be saved at this time', 422);  
   // }

    return $reply->load('owner');
hjortur17's avatar

Did not solve it, just caused more errors

Tray2's avatar

This is a similar test that I have in one of my applications

   /** @test */
    public function authors_first_name_is_required_to_store_an_author()
    {
        $this->signIn();
        $author = factory(Author::class)->make([
          'first_name' => null,
          'last_name' => 'Jordan'
      ]);

        $response = $this->post('/authors', $author->toArray())->assertSessionHasErrors(('first_name'));

        $this->assertEquals(0, Author::count());
    }

And my controller look something like this

public method store(Request $request)
{
   $request->validate(['first_name' => 'required', 'last_name' => 'required']);
   //Some more code here to store the author
}
hjortur17's avatar

@TRAY2 - Looks very similar but this line won't​ leave the party

Session is missing expected key [errors]

Doesn't​t matter what changes I make

sebraponi's avatar

In your controller you have:

request()->validate(['body' => 'required|spamfree']);

You can try to replace it with:

$this->validate(request(), ['body' => 'required|spamfree']);
1 like
sebraponi's avatar
Level 5

I had same problems with assertSessionHasErrors did not figured out exactly why. I believe you can check status because in controller you are sending 422:

$this->post($thread->path().'/athugasemdir', $reply->toArray())
            ->assertStatus(422);
4 likes
kova's avatar

I had similar problem. But problem was in my validation code. I had couple custom Rule class, and one of them throw FatalThrowableError because error in type declarations. So test cant find errors key in that exception because that not validation exception. If you still have same problem try to simplify validation code, i.e. just return 'body'=>'required' to see will the test passed

Lauro's avatar

I had the same problem, my error is in the phpunit.xml settings missing "<server name =" APP_ENV "value =" testing "/>"

tests
<filter>
    <whitelist processUncoveredFilesFromWhitelist="true">
        <directory suffix=".php">src</directory>
    </whitelist>
</filter>
<php>
    <server name="APP_ENV" value="testing"/>
</php>

scordill's avatar

I realize this is an old post, but you might try using withoutExceptionHandilng() to see if there is something else going on. Laravel might be handling an underlying exception for you.

Ganaa7's avatar

Maybe you fixed, if someone has occured this error you should check your router there is route set or not set!

PhilKz's avatar

I know this thread is old, but I had the same problem, and found a different cause (after a really long time). In my case, the test previously worked, then stopped working, without me making any changes to the test code. A series of related tests also failed. Specifically, when testing for a redirect, I also got the error:

Response status code [419] is not a redirect status code.

when testing a redirect that came after validation.

As it turns out, some other change I had made had caused Laravel to run its configuration caching. It seems this breaks Laravel's ability to disable its VerifyCsrfToken middleware during PHPUnit tests. The session failing to register errors was just a run-on effect of it running Csrf verification when it shouldn't.

The solution turns out to be:

  1. Run "php artisan config:clear"
  2. Never run "php artisan config:cache" or anything that might make it run, in development.

Further info: https://stackoverflow.com/questions/46325790/phpunit-expected-status-code-200-but-received-419-with-laravel#48281547 https://arievisser.com/blog/configuration-caching-caveats-in-laravel/

3 likes

Please or to participate in this conversation.