Skip to main content

Testing

During the development and testing phase, Laravel Captcha provides the fake method, allowing easy and efficient captcha response simulation.

Captcha::fake()

This method simulates the captcha behavior by providing a conversation that always passes. In other words, it pretends that the user has correctly filled the captcha. This is useful for testing your form's functionality without having to manually fill out the captcha every time.

Example:

use Rahul900day\Captcha\Facades\Captcha;
use Rahul900day\Captcha\Rules\Captcha as CaptchaRule;
use Illuminate\Support\Facades\Validator;

// call the fake method
Captcha::fake();

$validation = Validator::make($request, [
Captcha::getResponseName() => [
'required',
new CaptchaRule(),
],
]);

// perform a test assertion
$this->assertTrue(! $validation->fails()); // This will always pass.

In the above code snippet, $request could be an actual HTTP request object, or an associative array representing form data. Captcha::getResponseName() retrieves the name of the captcha response variable, and the captcha rule is applied to it.

Simulating a Fail

The fake method also accepts a boolean "fail" parameter. When set to false, the simulated captcha conversation will always fail. This is useful for testing how your application behaves when the user fails to correctly fill the captcha.

Example:

// Simulate a captcha failure
Captcha::fake(false);

Now, regardless of your form's inputs, the captcha will always fail. The test assertion assertTrue(! $validation->fails()) in the above example will always fail.