Test a specific FormRequest was used in Laravel

41 Views Asked by At

I am not looking to test validation against valid/invalid data. What I want to test is that a FormRequest's validation was used in a request.

// Controller
public function store(MyStoreRequest $request)
{
    // validation should have already happened once before this line.
    SomeModel::create($request->validated());

    return ...;
}
// Feature Test Class

// broken
public function test_store_method_uses_validation()
{
    $spy = $this->spy(MyStoreRequest::class);
    $uri = '...';
    $data = [...];   // valid or invalid data, results are the same
    $status = '...';

    $this
        ->postJson($uri, $data)
        ->assertStatus($status) // this breaks the test
    ;

    $spy->shouldHaveReceived('validated')->once();
}

This test does not work. The error given is from the query builder.

Illuminate\Database\Eloquent\Builder::create(): Argument #1 ($attributes) must be of type array, null given, called in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php on line 23


If I were to remove the assertion against the status, the test works but at this point I'm not sure if it's actually doing what it's supposed to.

// Feature Test Class

// works
public function test_store_method_uses_validation()
{
    $spy = $this->spy(MyStoreRequest::class);

    $this->postJson($uri, $data);

    $spy->shouldHaveReceived('validated')->once();
}
0

There are 0 best solutions below