测试断言 select 输入中有特定选项

Test to assert that a select input has specific options in it

假设我有一个名为 Dogs 的模型。我想确保当用户访问主页时,他们可以通过 select 输入 select 其中一只狗。我将如何在 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() 不是此处使用的正确方法。我想确保当用户进入主页时,那里有一个 select 输入,其中包含工厂创建的 5 个狗名。

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

$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());

我想你只想要狗的名字 table 没有别的,然后想断言看到它们要路由?

您也可以在只有 return 狗名的模型上创建自己的函数,就像这样。

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

然后在controller中调用这个函数

Dog::allNames();

现在您可以使用集合来声明它。或者您也可以压缩 return 集合。

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

控制器

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 路线的 blade 模板中,您可以做类似的事情

@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

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

编码愉快^_^