jacobcollinsdev's avatar

Feature Test - Expected a scalar, or an array as a 2nd argument

I'm creating a feature test for one of my models with the following code:

CollectionTest.php

/** @test*/
    public function a_collection_requires_a_description()
    {
        $user = User::factory()->create();

        $attributes = Collection::factory()->raw(['description' => '']);

        $this->actingAs($user)
            ->post('/collections', $attributes)
            ->assertSessionHasErrors('description'); //This is where the error is thrown
    }

CollectionFactory.php

public function definition()
    {
        return [
            'name' => fake()->firstName() . ' ' . fake()->lastName(),
            'description' => fake()->paragraph(),
            'filename' => 'https://picsum.photos/200/300',
            'release_date' => fake()->dateTimeBetween('-1 year', '+1 year'),
            'published_at' => fake()->dateTime()
        ];
    }

CollectionController.php

public function store()
    {
        request()->validate([
            'name' => 'required',
            'description' => 'required',
            'filename' => 'nullable',
            'release_date' => 'nullable',
            'published_at' => 'nullable',
        ]);

        Collection::create(request(['name', 'description']));

        return redirect('/collections');
    }

When I run the test, I receive the following error: Expected a scalar, or an array as a 2nd argument to "Symfony\Component\HttpFoundation\InputBag::set()", "DateTime" given.

The error is thrown at the assertSessionHasErrors function in the CollectionTest.php file. If I comment out everything except the name and description keys in the CollectionFactory.php file it works. Any thoughts on what could be causing this?

0 likes
5 replies
MohamedTammam's avatar

@jacobcollinsdev What if you do the following

$this->actingAs($user)
            ->post('/collections', ['description' => ''])
            ->assertSessionHasErrors(['description']);
jacobcollinsdev's avatar

@MohamedTammam That enables the test to pass, however I want to be able to test it as a model with the missing field as opposed to a simple key value pair. I don't understand why the code I wrote doesn't work.

MohamedTammam's avatar

@jacobcollinsdev TBH, it's the first time I see it the way to did. The post method should take a parameters that describe the request body.

I don't know what Collection::factory()->raw does in that case.

Please or to participate in this conversation.