Home > Software design >  Laravel custom validation rule mock in a test case
Laravel custom validation rule mock in a test case

Time:05-05

I have created a custom form request and it has this kind of a custom rule

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class ExampleUserRequest extends FormRequest
{
    public function rules()
    {
        return [
            'user_id' => [
                'required',
                 Rule::exists('items_table', 'id')
                    ->where(function ($query) use ($user_id) {
                        $query->where('user_id', $user_id);
                    }),                   
                }),        
            ],
        ];
    }
}

I need to mock this in my test class method since otherwise test case fails at this validation.

I tried to mock like this.

$ruleMock = Mockery::mock(Rule::class);
$ruleMock->shouldReceive('exists')->andReturn(true);

But it's not working.

CodePudding user response:

You should make valid requests to your endpoints, otherwise your are not testing anything, what if your controller actually needs a user_id ? You will get a 500 error down the line.

Better to use factories to create a test database that has everything you need, and transmit data that is valid and in your test database

  • Related