Behat / Mink Test to check if an element contains content

I am learning to write this test to improve the overall quality of the code I am writing, however I have not been able to find any example test that checks if an item contains anything - there are many tests that check for exact phrases.

In my case, this is a CMS driven application, so if the user changes content, the test will fail, so it seems more reasonable to check if there is any content on the page as regards the content.

I found a way to do it with selenium and jQuery, but it is much slower to run tests this way, and so I try, whenever possible, only on the command line.

Has anyone had experience with this kind of thing before? My application is written in PHP, I had some luck with some custom tests, but I am by no means an advanced coder.

+3


source to share


2 answers


If you are using Behat + Mink, you can use some of the built-in helper functions to accomplish this:

To assert that an element exists on the page:

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

      



Check 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

+6


source


The assertion that the page contains anything is not implemented in behact (I think) because it is not a good practice. The page may return an exception or HTTP 403/500 error and your test will pass.

  • If you just want the page to load OK check the page return code 200
Then the response status code should be

      



  • If you want to assert that the page contains something, rely on an element that is always present in the layout, eg. a footer (which at least checks that nothing has stopped rendering), an h1 page header, or even a "body" element (still deprecated if it contains an error message)
Then I should see a ".footer" element
Then I should see a "body" element

      

+2


source







All Articles