Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example of fail() to Custom Expectation #254

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions custom-expectations.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Custom expectations are usually defined in the `tests/Pest.php` file, but you ca
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()`:

```php
// Pest.php or Expectations.php...
// Pest.php or Expectations.php
expect()->extend('toBeWithinRange', function (int $min, int $max) {
return $this->toBeGreaterThanOrEqual($min)
->toBeLessThanOrEqual($max);
Expand All @@ -35,7 +35,7 @@ expect()->extend('toBeWithinRange', function (int $min, int $max) {
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.

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

Expand All @@ -51,6 +51,25 @@ test('numeric ranges', function () {
});
```

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.

```php
// Pest.php or Expectations.php
expect()->extend('toBeDivisibleBy', function (int $divisor) {
if ($divisor === 0) {
test()->fail('The divisor cannot be 0.');
}

return expect($this->value % $divisor)->toBe(0);
});

// Tests/Unit/ExampleTest.php
test('numeral division', function () {
expect(10)->toBeDivisibleBy(2); // Pass
expect(10)->toBeDivisibleBy(0); // Fail "The divisor cannot be 0."
});
```

## Intercept Expectations

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`.
Expand Down