Search code examples
laravelphpunitlaravel-7laravel-testing

Laravel test not passing


So I'm learning doing tests for my application and one of the tests it doesn't want to pass, and here it is the logic: Basically, when a user request the home page, I expect that the database list count would be 0, and this passed, then I expect also that the session has an error key of NoBook and here it fails. this is the code that i have tried:

class BookDisplayManagmentTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function Show_error_message_when_there_is_no_book_to_display_in_index_page()
    {
        //Request the home page
        $response = $this->get(route('home'));

        // I expect the count on the database book equal 0
        $this->assertCount(0, book::all());

        //Then I also expect that the session will flash an error with key NoBook
        $response->assertSessionHasErrors('NoBook');
    }

}

But the problem I'm getting this error:

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

And the code that add the session error:

<?php

namespace App\Http\Controllers;

use App\Books;
use Illuminate\Http\Request;

class IndexController extends Controller
{
      /** @show index function */
        public function index()
        {
            $book = Books::paginate(7);
            if(!$book->count())
            {
                session()->now('NoBook','There is no books at the moment');
            }
            return view('index', compact('book'));
        }
}

Solution

  • You are using session() which is adding a key to the session which is not an error key.

    Therefore, since you are not passing an error from your Controller - then your test is "successfully" failing.

    If you want to pass on an error to the session, you have to use MessageBag such as using the following code:

          /** @show index function */
            public function index()
            {
                $book = Books::paginate(7);
                $errors = [];
    
                if(!$book->count())
                {
                    $errors['NoBook'] = 'There is no books at the moment';
                }
                return view('index', compact('book'))->withErrors($errors);
            }