【问题标题】:Test to assert that a select input has specific options in it测试以断言选择输入中包含特定选项
【发布时间】:2020-11-28 04:36:36
【问题描述】:

假设我有一个名为 Dogs 的模型。我想确保当用户访问主页时,他们可以从选择输入中选择其中一只狗。我将如何在 Laravel 中进行测试?这是我目前所拥有的。

    public function a_user_can_select_a_dog()
    {
        $this->withoutExceptionHandling();

        $dogs = App\Dog::all();

        $names = $dogs->map(function ($dog) {
            return $dog->name;
        });

        $response = $this->get(route('home'))->assertSee($names);
    }

最终,assertSee 中的内容是我所缺少的。或者assertSee() 可能不是在这里使用的正确方法。我想确保当用户进入主页时,那里有一个选择输入,其中包含工厂创建的 5 个狗名。

【问题讨论】:

    标签: php laravel testing phpunit


    【解决方案1】:

    我认为您应该做的是传递数据并像这样在刀片模板中处理它

    控制器

    public function a_user_can_select_a_dog()
    {
         //i don't know about the first line so i kept it just because 
         //i saw it on the original code but if it is for this operation then its not 
         //really necessary
    
         $this->withoutExceptionHandling();
        $dogs = App\Dog::all();
        return redirect('/home')->with('dogs' , $dogs);
    }
    

    然后在代表 /home 路由的刀片模板中,您可以执行类似的操作

    @if(count($dogs > 1))
        <label>Please Select Dog Name</label>
        <select>
         @foreach($dogs as $dog)
          <option>{{ $dog->name }}</option>
         @endforeach
        </select>
    @else
    <h1>No Dogs Were Found</h1>
    @endif
    

    这只是一个示例刀片模板是非常强大的工具确保您使用它 请参阅 if 语句部分下方的docs,您会发现循环

    快乐编码^_^

    【讨论】:

      【解决方案2】:

      我想你只想要狗表中的狗名,然后想要断言看到它们路由?

      你也可以在模型上创建自己的函数,只返回狗的名字,像这样。

      public static function allNames($columns = ['*'])
      {
          return Dog::pluck('name');
      }
      

      然后在控制器中调用这个函数。

      Dog::allNames();
      

      现在您可以使用集合来断言它。或者你也可以压缩返回集合。

      【讨论】:

      • 这里$columns函数参数的作用是什么?它从未在实现中使用。
      • 这个参数可以去掉,我忘记去掉了。
      【解决方案3】:

      我猜你只是想做类似的事情,使用你刚刚创建的狗来确保它们的名字出现在主页上。

      $response = $this->get(route('home'));
      
      $dogs->each(function (Dog $dog) use($response) {
          $response->assertSee($dog->name);
      });
      

      您还可以更精确地指定文本的顺序,通过调用assertSeeInOrder(),这需要一个文本数组来查找。

      $response->assertSeeInOrder($dogs->map(function (Dog $dog) {
          return "$dog->name";
      })->all());
      

      【讨论】:

      • 有没有办法将所有名称压缩到一个集合中并针对该集合进行断言?
      • 我用更多的案例更新了答案,我不知道你的意思是收集反对收集,你的回复是文本,所以至少我们必须处理:)
      • 用一个更好的例子来更新我的问题。我不关心输入标记 - 只想确保名称出现在页面上。
      • 更新了示例,您似乎对一个解决方案非常挑剔,因为第一个示例将完美运行。否则你必须使用 seeInOrder。
      猜你喜欢
      • 2020-08-01
      • 2021-01-14
      • 1970-01-01
      • 2014-02-23
      • 2021-04-16
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      • 2016-08-06
      相关资源
      最近更新 更多