You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: custom-expectations.md
+21-2Lines changed: 21 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -12,7 +12,7 @@ Custom expectations are usually defined in the `tests/Pest.php` file, but you ca
12
12
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()`:
13
13
14
14
```php
15
-
// Pest.php or Expectations.php...
15
+
// Pest.php or Expectations.php
16
16
expect()->extend('toBeWithinRange', function (int $min, int $max) {
17
17
return $this->toBeGreaterThanOrEqual($min)
18
18
->toBeLessThanOrEqual($max);
@@ -35,7 +35,7 @@ expect()->extend('toBeWithinRange', function (int $min, int $max) {
35
35
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.
36
36
37
37
```php
38
-
// Pest.php or Expectations.php...
38
+
// Pest.php or Expectations.php
39
39
expect()->extend('toBeWithinRange', function (int $min, int $max) {
40
40
// Assertions based on `$this->value` and the given arguments...
41
41
@@ -51,6 +51,25 @@ test('numeric ranges', function () {
51
51
});
52
52
```
53
53
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
+
54
73
## Intercept Expectations
55
74
56
75
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