feat: add toBeEmail expectation (#1735)

Adds `toBeEmail()` backed by `filter_var(FILTER_VALIDATE_EMAIL)`.
Mirrors the existing `toBeUrl()` pattern — no new dependencies, pure PHP.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Sonali dudhia
2026-06-24 20:21:35 +05:30
committed by GitHub
parent 5cfb4133bf
commit b49cd150c9
3 changed files with 48 additions and 0 deletions
+16
View File
@@ -1171,6 +1171,22 @@ final class Expectation
return $this; return $this;
} }
/**
* Asserts that the value is an email address.
*
* @return self<TValue>
*/
public function toBeEmail(string $message = ''): self
{
if ($message === '') {
$message = "Failed asserting that {$this->value} is an email address.";
}
Assert::assertTrue(Str::isEmail((string) $this->value), $message);
return $this;
}
/** /**
* Asserts that the value is a url * Asserts that the value is a url
* *
+8
View File
@@ -118,6 +118,14 @@ final class Str
return sprintf(str_repeat('`%s` → ', count($describeDescriptions)).'%s', ...$descriptionComponents); return sprintf(str_repeat('`%s` → ', count($describeDescriptions)).'%s', ...$descriptionComponents);
} }
/**
* Determine if a given value is a valid email address.
*/
public static function isEmail(string $value): bool
{
return (bool) filter_var($value, FILTER_VALIDATE_EMAIL);
}
/** /**
* Determine if a given value is a valid URL. * Determine if a given value is a valid URL.
*/ */
+24
View File
@@ -0,0 +1,24 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect('user@example.com')->toBeEmail()
->and('notanemail')->not->toBeEmail();
});
test('failures', function () {
expect('notanemail')->toBeEmail();
})->throws(ExpectationFailedException::class);
test('failures with custom message', function () {
expect('notanemail')->toBeEmail('oh no!');
})->throws(ExpectationFailedException::class, 'oh no!');
test('failures with default message', function () {
expect('notanemail')->toBeEmail();
})->throws(ExpectationFailedException::class, 'Failed asserting that notanemail is an email address.');
test('not failures', function () {
expect('user@example.com')->not->toBeEmail();
})->throws(ExpectationFailedException::class);