I have a deliverypoint
resource in my laravel project. The controller code associated to the route deliverypoints.index
is straightforward:
public function index()
{
return view('deliverypoints.index', [
'deliverypoints' => DeliveryPoint::all(),
]);
}
With the view deliverypoints.index
:
@extends('layouts.app')
@section('content')
<div class="container">
<ul class="row">
@foreach ($deliverypoints as $deliverypoint)
<li class="col-12">{{ $deliveryPoint->id }}</li>
@endforeach
</ul>
</div>
@endsection
Here you can see a typo in the li
tag: deliveryPoint->id
instead of deliverypoint->id
. This causes an "undefined variable" error when I manually test the route in my browser: so far, so good.
My problem is that when testing the route with PHPUnit, the test passes instead of reporting the error. Here is the code of the feature test:
public function testIndex()
{
$response = $this->get(
route('deliverypoints.index')
);
$response->assertSuccessful()->assertViewIs(
'deliverypoints.index'
)->assertViewHasAll(
['deliverypoints']
);
}
Since the test passes, I guess the view is successfully returned by the server, but I would expect the typo to be detected.
How can I enforce the test to make it see such errors?
I'm using laravel v5.6 with PHP v7.1.18 and PHPUnit v7.2.6.
EDIT:
I tried to clear cache using:
php artisan cache:clear
php artisan view:clear
php artisan route:clear
But still the error remains undetected.
I found the answer: the database wasn't seeded with DeliveryPoint
instances. So the controller send an empty array to the view through DeliveryPoint::all
and the loop:
@foreach ($deliverypoints as $deliverypoint)
<li class="col-12">{{ $deliveryPoint->id }}</li>
@endforeach
wasn't executed, silenting the error.
A possible fix using factories:
public function testIndex()
{
factory(DeliveryPoint::class)->create(); // seed the database
$response = $this->get(
route('deliverypoints.index')
);
$response->assertSuccessful()->assertViewIs(
'deliverypoints.index'
)->assertViewHasAll(
['deliverypoints']
);
}
I'd suggest to add a 200 check before going any further
$this->assertEquals(200, $response->status());
I have tried to replicate the issue you have and the response is the same in the test than in the browser: 500 response in both cases.