drupalbehatmink

How to check for (any) IP address in Behat/Mink?


I'm using Behat/Mink to test a Drupal 8 site.

I have an input field with an IP address and I want to make sure that the IP address has been recorded. I don't want to check for a specific IP address because it might change, so I just want to ensure the field has some value.

Based on the assumption the IP address will include a period, I tried this:

 Then the "#edit-field-ip-0-value" element should contain "."

But this fails with the error:

    The string "." was not found in the HTML of the element matching css "#edit-field-ip-0-value". (Behat\Mink\Exception\ElementHtmlException)

However, the value of the field is:

172.19.0.1

So there is a period; I don't understand why "contains" doesn't see it.

I also tried checking like this:

 Then the "#edit-field-ip-0-value" element should contain "0"

But it fails with the same error (string not found in the HTML of the element).

EDIT

This is the HTML I am trying to target:

<input class="js-text-full text-full form-text" data-drupal-selector="edit-field-ip-0-value" type="text" id="edit-field-ip-0-value" name="field_ip[0][value]" value="172.19.0.1" size="60" maxlength="255" placeholder="">

Solution

  • Here's the code I ended up using:

      /**
       * @Then the :element element should contain an IP address
       *
       * Checks that the element with the specified CSS contains IP address value.
       */
      public function assertElementContainsIpAddress($element) {
        $page = $this->getSession()->getPage();
        // Alternately, substitute with getText() for the label.
        $element_value = $page->find('css', "$element")->getValue();
        $valid_ip_address = filter_var($element_value, FILTER_VALIDATE_IP);
        if ($valid_ip_address === FALSE) {
          throw new Exception("Valid IP address not found in element $element, which had a value of $element_value.");
        }
      }