diff --git a/src/Asserts/Traits/UsesElementAsserts.php b/src/Asserts/Traits/UsesElementAsserts.php index 7daeb4d..3d0c375 100644 --- a/src/Asserts/Traits/UsesElementAsserts.php +++ b/src/Asserts/Traits/UsesElementAsserts.php @@ -73,6 +73,23 @@ public function find(string $selector, $callback = null): self return $this; } + public function findAll(string $selector, $callback): self + { + $elements = $this->getParser()->queryAll($selector); + Assert::assertNotCount( + 0, + $elements, + sprintf('Could not find any matching element for selector "%s"', $selector) + ); + + foreach ($elements as $element) { + $elementAssert = new AssertElement($this->getContent(), $element); + $callback($elementAssert); + } + + return $this; + } + public function contains(string $selector, $attributes = null, $count = 0): self { Assert::assertNotNull( diff --git a/tests/DomTest.php b/tests/DomTest.php index a6c472d..b9a7bdb 100644 --- a/tests/DomTest.php +++ b/tests/DomTest.php @@ -268,6 +268,22 @@ }); })->throws(AssertionFailedError::class, 'Could not find a matching "div" with data:'); +it('can run assertions against all elements that match the selection', function () { + $this->get('form') + ->assertOk() + ->assertElementExists(fn (AssertElement $view) => $view + ->findAll('select', fn (AssertElement $select) => $select->has('name')) + ); +}); + +it('fails when findAll is used but no elements match the selector', function () { + $this->get('form') + ->assertOk() + ->assertElementExists(fn (AssertElement $view) => $view + ->findAll('img', fn (AssertElement $image) => $image->has('alt')) + ); +})->throws(AssertionFailedError::class); + it('can find a nested element with content functional', function () { $this->get('nesting') ->assertElementExists(function (AssertElement $element) {