mewebstudio / captcha

Captcha for Laravel 5/6/7/8/9/10/11
MIT License
2.46k stars 453 forks source link

test forms with captcha #218

Closed hamidrasti closed 3 years ago

hamidrasti commented 3 years ago

Hi. First of all, thanks for this great package.

Is there any way to test forms with captcha? (is there any way to generate test captcha?)

to able to write test like this:

public function test_should_store_contacts_when_everything_is_ok()
    {
        $testCaptcha = 'TEST1';

        $response = $this->withSession([])
            ->post(route('contacts.store'), [
                'message' => 'my message',
                'captcha' => $testCaptcha
            ]);

        $response->assertCreated();
    }
hamidrasti commented 3 years ago

I ended up this issue with mocking form request:

public function test_should_store_contacts_when_everything_is_ok()
    {
        $testInput = [
            'message' => 'my_message',
            'captcha' => 'test1',
        ];
        $this->withoutExceptionHandling();

        $this->mock(ContactRequest::class, function ($mock) use ($testInput) {
            $mock->shouldReceive('passes')->andReturn(true);
            $mock->shouldReceive('validated')->andReturn($testInput);
        });

        $response = $this->post(route('contacts.store'), $testInput);

        $response->assertRedirect();
        $this->assertDatabaseHas('contacts', [
            'message' => $testInput['message'],
        ]);
    }
antoinelame commented 3 years ago

@hamraa By mocking your entire request validation class, the issue is that you are not testing your other rules.

You can do that instead:

public function can_submit_a_message()
{
    // Mock captcha verification
    app('validator')->extend('captcha', fn () => true);

    // Your test...
    $form = [
        'message' => 'my_message',
        'captcha' => 'anything',
    ];

    $this->post('/contact', $form)->assertOk();
}

Your captcha will always be validated.

davide-casiraghi commented 2 years ago

Did someone manage to test forms with a captcha that are into a livewire component?