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 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败