Skip to content

Commit 9534449

Browse files
authored
Merge pull request #254 from pestphp/add_fail_custom_expectation
Add example of fail() to Custom Expectation
2 parents 5e25c0e + 8d1def5 commit 9534449

1 file changed

Lines changed: 21 additions & 2 deletions

File tree

custom-expectations.md

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Custom expectations are usually defined in the `tests/Pest.php` file, but you ca
1212
For example, suppose you are testing a number utility library and you need to frequently assert that numbers fall within a given range. In this case, you might create a custom expectation called `toBeWithinRange()`:
1313

1414
```php
15-
// Pest.php or Expectations.php...
15+
// Pest.php or Expectations.php
1616
expect()->extend('toBeWithinRange', function (int $min, int $max) {
1717
return $this->toBeGreaterThanOrEqual($min)
1818
->toBeLessThanOrEqual($max);
@@ -35,7 +35,7 @@ expect()->extend('toBeWithinRange', function (int $min, int $max) {
3535
Of course, you probably want users to have the ability to "chain" expectations together with your custom expectation. To achieve this, ensure your custom expectation includes a `return $this` statement.
3636

3737
```php
38-
// Pest.php or Expectations.php...
38+
// Pest.php or Expectations.php
3939
expect()->extend('toBeWithinRange', function (int $min, int $max) {
4040
// Assertions based on `$this->value` and the given arguments...
4141

@@ -51,6 +51,25 @@ test('numeric ranges', function () {
5151
});
5252
```
5353

54+
Sometimes, you may need to trigger a test failure in your Custom Expectation. To do so, use the `test()` method in combination with the [`fail()`](/docs/exceptions) method.
55+
56+
```php
57+
// Pest.php or Expectations.php
58+
expect()->extend('toBeDivisibleBy', function (int $divisor) {
59+
if ($divisor === 0) {
60+
test()->fail('The divisor cannot be 0.');
61+
}
62+
63+
return expect($this->value % $divisor)->toBe(0);
64+
});
65+
66+
// Tests/Unit/ExampleTest.php
67+
test('numeral division', function () {
68+
expect(10)->toBeDivisibleBy(2); // Pass
69+
expect(10)->toBeDivisibleBy(0); // Fail "The divisor cannot be 0."
70+
});
71+
```
72+
5473
## Intercept Expectations
5574

5675
Although it is considered an advanced practice, you can override existing expectations with your own implementation via the `intercept()` method. When using this method, the existing expectation will be fully substituted if the expectation value is of the specified type. For example, you can replace the `toBe()` expectation to check if two objects of the `Illuminate\Database\Eloquent\Model` type have the same `id`.

0 commit comments

Comments
 (0)