rajeshtva's avatar

Assertsee function test passing correctly even when it should fail

I have a simple test in which i am creating a model instance and then. i am visiting a route to check the details of that model object. i have just defined a controller file and there is no function defined in there. The view file is not created. then i am asserting to see some string in the blade file. l am sharing all codes. yet i see all test passing when it should fail.

test case

<?php

namespace Tests\Feature;

use App\Models\Concert;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
use Throwable;

class ViewTicketConcertListing extends TestCase
{

    use RefreshDatabase;

    /** @test */
    public function user_can_view_a_concert_listing()
    {
        // Arrange 
        $concert = Concert::create([
            'title' => 'The Red Chord',
            'subtitle' => 'with Animosity and Lethargy',
            'date' => Carbon::parse('December 13, 2016 8:00pm'),
            'ticket_price' => 3250, // better way to store currency ( in lowest possible rate)
            'venue' => 'The Mosh Pit',
            'venue_address' => '123 Lane Street',
            'city' => 'Laraville',
            'state' => 'ON',
            'zip' => '17916',
            'additional_information' => 'For tickets, call (555) 555-5555',
        ]);


        // Act 
        // $this->withoutExceptionHandling();
        $response = $this->get('/concerts/' . $concert->id);


        // Assert 
        $response->assertSee('The Red Chord');
        $response->assertSee('with Animosity and Lethargy');
        $response->assertSee('December 13, 2016 8:00pm');
        $response->assertSee('32.50');
        $response->assertSee('The Mosh Pit');
        $response->assertSee('123 Lane Street');
        $response->assertSee('Laraville');
        $response->assertSee('ON');
        $response->assertSee('17916');
        $response->assertSee('For tickets, call (555) 555-5555');
    }
}

routes/web.php

Route::get('/concerts/{concert}', [ConcertsController::class, 'show']);

`app\Http\Controllers\ConcertsController.php'

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ConcertsController extends Controller
{
    //
}

as it can be seen that nothing is defined here. yet i see all test passing.


> Executing task: /home/rex/rajesh/code/ticketbeast/vendor/bin/phpunit /home/rex/rajesh/code/ticketbeast/tests/Feature/ViewTicketConcertListing.php --filter '^.*::user_can_view_a_concert_listing( .*)?$' <

PHPUnit 9.5.2 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 00:00.348, Memory: 14.00 MB

OK (1 test, 10 assertions)

Terminal will be reused by tasks, press any key to close it.

but when i add $this->withoutExceptionHandling() in the test. then i see correct error. i know that the test should fail yet it is passing. is there something i am missing during testing ??

I am using laravel 8 with default packages.

UPDATE: now i made show function and returned a view instance. but the blade file is not created yet. still the test is passing.

0 likes
6 replies
Tray2's avatar

This happens to me as well. I think it has to do with the error page that Laravel displays by default when an error occurs.

Just add this at the top of your tests.

$this->withoutExceptionHandling();

Once the test pass for real you can remove it.

1 like
rajeshtva's avatar

@tray2 good morning. yes it does work. now i am dumping all string that i am getting in the response using

$a = $response->getContent(); 
$file = 'file.txt';
file_put_contents($file, $a);

and i can clearly see that all strings are there. but @tray2 sir. is there any way that i can reliably check that if some error/exception occurs then i can see where it occured because i have seen $this->withoutExceptionHandling() method to throw errors even when it was supposed to pass.

Tray2's avatar
Tray2
Best Answer
Level 74

That is the trade off, unfortunately.

I take it you are doing feature tests.

You could maybe do an assertion on something that does not exists in your view but does in the graceful exception handling from Laravel.

$this->assertNotSee();

I always turn off the exception handling until I get the test to pass and then turn it back on. There might be cases where it fails the test due to the turned off exception handling but you shouldn't use it in the finished test.

rajeshtva's avatar

@tray2 ok i get it.. then my test should be like.. always start with $this->withoutExceptionHandling() then my test case passes then i should remove it.. please correct me if i am wrong.

Tray2's avatar

That is the way I do it for most my feature tests.

lukas653's avatar

Hi, I am trying to manage this example too, but my data is not passed to the controller as I understand. If I try to retrieve all records from DB in the test I receive collection Concert::all(). I get an error below, how could I fix it?

  <h2></h2>\n
  <p></p>\n
  \n
  <p>Doors at </p>\n
  \n
  <p>0.00</p>\n
  <p></p>\n
  <p></p>\n
  <p>,  </p>\n
  <p></p>\n
  ' contains "The Red Chord".

My controller:

 public function show(Concert $concert)
    {
        return view('concerts.show', ["concert" => $concert]);
    }

Blade:

<h1>{{ $concert->title }}</h1>
<h2>{{ $concert->subtitle }}</h2>
<p>{{ $concert->date }}</p>
{{--<p>{{ $concert->date->format('F j, Y') }}</p>--}}
<p>Doors at {{ $concert->date }}</p>
{{--<p>Doors at {{ $concert->date->format('g:ia') }}</p>--}}
<p>{{ number_format($concert->ticket_price / 100, 2) }}</p>
<p>{{ $concert->venue }}</p>
<p>{{ $concert->venue_address }}</p>
<p>{{ $concert->city }}, {{ $concert->state }} {{ $concert->zip }}</p>
<p>{{ $concert->additional_information }}</p>

Test

<?php

namespace Tests\Feature;

use App\Models\Concert;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\Concerns\InteractsWithViews;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ViewConcertListingTest extends TestCase
{
    use DatabaseMigrations;

    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function test_example()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }

    /** @test */

    public function user_can_view_a_concert_listing()
    {
        $this->withoutExceptionHandling();
        // Arrange (any setup needed for a test)
        // Create a concert

        $concert = Concert::create([
            'title' => 'The Red Chord',
            'subtitle' => 'with Animosity and Lethargy',
            'date' => Carbon::parse('December 13, 2020 8:00pm'),
            'ticket_price' => 3250,
            'venue' => 'The Mosh Pit',
            'venue_address' => '123 Example Lane',
            'city' => 'Laraville',
            'state' => 'ON',
            'zip' => '17916',
            'additional_information' => 'For tickets, call (555) 555-5555.',
        ]);

         // Act (run the code that we want to test the outcome of)

        $response = $this->get('/concerts/' . $concert->id);

        // Assert

        $response->assertStatus(200);
        $response->assertSee('The Red Chord');
        $response->assertSee('with Animosity and Lethargy');
        $response->assertSee('December 13, 2016');
        $response->assertSee('8:00pm');
        $response->assertSee('32.50');
        $response->assertSee('The Mosh Pit');
        $response->assertSee('123 Example Lane');
        $response->assertSee('Laraville, ON 17916');
        $response->assertSee('For tickets, call (555) 555-5555.');
    }
}

Testing phpunit.xml

<server name="APP_ENV" value="testing"/>
        <server name="BCRYPT_ROUNDS" value="4"/>
        <server name="CACHE_DRIVER" value="array"/>
        <env name="DB_CONNECTION" value="sqlite"/>
        <env name="DB_DATABASE" value=":memory:"/>
        <server name="MAIL_MAILER" value="array"/>
        <server name="QUEUE_CONNECTION" value="sync"/>
        <server name="SESSION_DRIVER" value="array"/>
        <server name="TELESCOPE_ENABLED" value="false"/>

Please or to participate in this conversation.