duaiwu8385 2018-08-10 09:31
浏览 41
已采纳

测试laravel路径时,视图中的静默未定义变量

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.

  • 写回答

2条回答 默认 最新

  • dtcyv3985 2018-08-10 13:10
    关注

    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']
        );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波