Search code examples
phpdrupalautomated-testsbehat

Click on a tab that has href, by taking text rather than xpath for behat testing


This is my code in the FeatureContext file.

public function iClickOnTheText2($arg1)
    {
        $session = $this->getSession();
        $element = $session->getPage()->find('xpath',$session->getSelectorsHandler()->selectorToXpath('xpath', $arg1));
        if (null == $element) {
            throw new InvalidArgumentException(sprintf('Cannot find text: "%s"', $arg1));
        }

        $element->click();
    }

this is my behat.yml file

default:
  suites:
    default:
      path: %paths.base%/features/bootstrap
      contexts: 
        - FeatureContext
  extensions:
    Behat\MinkExtension:
      base_url: http://somedevwebsite.ca
      sessions:
        default:
          goutte: ~

My main aim is to click on a text that appears as a tab option on the page so that i can open up the tab. I am trying to get a hold of the text so that i can click on the text. any other way to do this will also be appreciated, but i am trying not to use the xpath as i will have to copy a lot of xpaths. but trying to find the xpath for a particular text and using that for the click is alright. just let me know what is wrong with this, as the error i am getting is when my feature contains a step When I click on the text "Members" This is the error I get

When I click on the text "Members"                 # FeatureContext::iClickOnTheText2()
      Cannot find text: "Members" (InvalidArgumentException)

Thank you


Solution

  • The find() method can make use of several different selector mechanisms such as xpath, but also by HTML ID, element name, text content, CSS selector and so on.

    There are also a number of shortcuts for the find() method, such as findLink() which simplify common use cases such as finding a link by name.

    In your example you could replace the xpath with the following:

    $element = $session->getPage()->findLink($arg1);
    

    This will work as long as $arg1 is the html ID, title or text content of the link, which should work with the 'Membership' tab in your example.

    You can find out more about the find() method, selectors, and shortcuts in the Mink handbook section on traversing pages: http://mink.behat.org/en/latest/guides/traversing-pages.html

    For more advanced usage the Drupal Behat Extension provides a number of out-of-the-box integrations for Drupal, Behat and Drush. It also includes common Behat statements such as clicking links. In this case with the Drupal Behat Extension you could use: When I follow "Membership"