2

I'm working on a legacy code and trying to use tests to cover the code for later refactoring. In one controller there's a piece of code like this:

return redirect()->route('login')->withErrors(['invalid credentials']);

Here are my assertions for the test:

$response->assertRedirect(route('login'));
$response->assertSessionHasErrors([
    0 => 'invalid credentials'
]);

But the problem is I get the following output:

Session missing error: 'invalid credentials'
Failed asserting that false is true.

Any idea how can I get this done?

1 Answer 1

3

Looking at the source code of assertSessionHasErrors() I think it cannot be done with your use case. The problem is the unnamed array in your withErrors(...) method. I see two options for you:

  • Change your legacy application into:
return redirect()->route('login')->withErrors(['error' => 'invalid credentials']);

Afterwards you can run your test like so:

$response->assertRedirect(route('login'));    
$response->assertSessionHasErrors([
    'error' => 'invalid credentials'
]);
  • If you cannot change your legacy application you could use this:
$response->assertRedirect(route('login'));    
$this->assertEquals(session('errors')->getBag('default')->first(),'invalid credentials');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.