From e91c85496f078e50b61873ab5915934655b1faa6 Mon Sep 17 00:00:00 2001 From: Luke Downing Date: Sun, 23 Jan 2022 23:37:03 +0000 Subject: [PATCH] Adds support for `scoped` in HigherOrderExpectations. --- src/Expectations/HigherOrderExpectation.php | 16 ++++++++++++++++ tests/Features/Expect/HigherOrder/methods.php | 17 +++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/Expectations/HigherOrderExpectation.php b/src/Expectations/HigherOrderExpectation.php index 83c43643..7fb0300e 100644 --- a/src/Expectations/HigherOrderExpectation.php +++ b/src/Expectations/HigherOrderExpectation.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Pest\Expectations; +use Closure; use Pest\Concerns\Retrievable; use Pest\Expectation; @@ -79,6 +80,21 @@ final class HigherOrderExpectation return $this->expect($value); } + /** + * Scope an expectation callback to the current value in + * the HigherOrderExpectation chain. + * + * @param Closure(Expectation): void $expectation + * + * @return HigherOrderExpectation + */ + public function scoped(Closure $expectation): self + { + $expectation->__invoke($this->expectation); + + return new self($this->original, $this->original->value); + } + /** * Dynamically calls methods on the class with the given arguments. * diff --git a/tests/Features/Expect/HigherOrder/methods.php b/tests/Features/Expect/HigherOrder/methods.php index d6da636b..ad6cf952 100644 --- a/tests/Features/Expect/HigherOrder/methods.php +++ b/tests/Features/Expect/HigherOrder/methods.php @@ -74,6 +74,23 @@ it('works with higher order tests') ->name()->toEqual('Has Methods') ->books()->each->toBeArray; +it('can use the scoped method to lock into the given level for expectations', function () { + expect(new HasMethods()) + ->attributes()->scoped(fn ($attributes) => $attributes + ->name->toBe('Has Methods') + ->quantity->toBe(20) + ) + ->name()->toBeString()->toBe('Has Methods') + ->newInstance()->newInstance()->scoped(fn ($instance) => $instance + ->name()->toBe('Has Methods') + ->quantity()->toBe(20) + ->attributes()->scoped(fn ($attributes) => $attributes + ->name->toBe('Has Methods') + ->quantity->toBe(20) + ) + ); +}); + class HasMethods { public function name()