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

Viewed 569

Assuming I have a model called Dogs. I want to ensure that when a user visits the home page, they can select one of the dogs from a select input. How would I test this in Laravel? here's what I have so far.

    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);
    }

ultimately what goes into the assertSee is what I am missing. Or perhaps assertSee() isn't the correct method to use here. I want to make sure that when the user goes to the home page there is a select input there with the 5 dog names that were created by the factory.

3 Answers

I guess you simply wanna do something similar to this, using the dogs you just created to assure their names are present on the home page.

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

$dogs->each(function (Dog $dog) use($response) {
    $response->assertSee($dog->name);
});

Even more precise you can also specify the order of the text, with the call to assertSeeInOrder(), this takes an array of texts to find.

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

I think you only want the dog name from the dog table nothing else and then want to assertSee them to route?

You can also create your own function on the model which only return the dog names, like this.

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

and then call this function in controller.

Dog::allNames();

now you can use the collection to assert it. or you can also compact the return collection.

i think what you should do is pass the data and deal with it in your blade template like so

Controller

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);
}

then in your blade template which represents /home route you can do something similar to this

@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

this is just an example blade template is very powerful tool make sure you use it refer to docs underneath the if statements section you will find loops

Happy Coding ^_^

Related