Behat/Mink Test to check if element contains content

changeableface picture changeableface · Dec 8, 2014 · Viewed 8.9k times · Source

I'm learning to write these test to help increase overall quality of the code I write, however I've been unable to find any example of a test that checks to see if an element contains anything - there are plenty of test that check for exact phrases.

In my case it's a CMS driven application, so if the user changes the content the test will fail, so it's seems more reasonable to check to make sure there is some content in the page, regards of the content.

I've found a way to do with this selenium and jQuery, but it's a lot slower to run tests this way, and so I'm trying where possible to keep to command line only.

Any one had experience with this sort of thing before? My application is written in PHP, I've had a bit of luck with some custom tests actions, but I'm by no means a advanced coder.

Answer

Rob Squires picture Rob Squires · Dec 10, 2014

If you're using Behat + Mink you could use some of the built in helper functions to achieve this:

Assert the element exists on the page:

$this->assertSession()->elementExists('css', '.selector');

Check the content is not empty:

if ( empty($this->getPage()->find('css', '.selector')->getText()) ) {
    throw new Exception;
}

I find the WebAssert class to be a particularly useful object + the best documentation is the class itself: WebAssert.php