Design, Programming, Projects, Technology

Simple Method for Checking for Order With Behat

While needing to write a test to check the order of 2 items (within a given CSS query) in Behat, I did a little googling and came across this website here.

The tutorial is great and i just wanted to give a shout out to the author for their great content. I also made a slight change to include testing for the existing of the 2 items.

Here is my slightly updated version:

    /**
     * 
     * @Then /^"([^"]*)" should precede "([^"]*)" for the query "([^"]*)"$/
     */
    public function shouldPrecedeForTheQuery($textBefore, $textAfter, $cssQuery)
    {
		// http://neverstopbuilding.net/simple-method-for-checking-for-order-with-behat/
        $items = array_map(
            function ($element) {
                return $element->getText();
            },
            $this->getPage()->findAll('css', $cssQuery)
        );

		WebTestCase::assertTrue(in_array($textBefore, $items), 'The before text was not found!');
		WebTestCase::assertTrue(in_array($textAfter,  $items), 'The after text was not found!');
			
        WebTestCase::assertGreaterThan(
            array_search($textBefore, $items),
            array_search($textAfter, $items),
            "$textBefore does not proceed $textAfter"
        );
    }

You can see an example of the test i wrote using this method here.