Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for each element with behat or codeception

I want to test a website which has a dynamic menustructure. I want to loop through all menuitems and run the same series of test on every page. We're talking about 100+ pages that change reguraly.

I would like to do this with either behat or codeception.

Does anybody have an idea about how to do this?

like image 438
Jeroen Avatar asked Nov 03 '22 22:11

Jeroen


2 Answers

When using Behat with Mink, you can grab your menu items with findAll() and then iterate over it:

/**
 * @When /^I run my test series for all menu items$/
 */
public function iRunMyTestSeriesForAllMenuItems() {

    $result = TRUE;
    $this->getSession()->visit('http://www.example.com/');
    $links = $this->getSession()->getPage()->findAll('css', '#menu ul li a');
    foreach ($links as $link) {
        $url = $link->getAttribute('href');
        if (FALSE === $this->yourTestHere($url)) {
            $result = FALSE;
        }
    }

    return $result;
}
like image 200
stmllr Avatar answered Dec 11 '22 09:12

stmllr


I had a similar use case where I wanted to visit all pages of a given site map making sure there isn't any dead links. I had the approach to dynamically generate an array of steps which is then returned and processed by Behat. I had to add an artificial step "I print out page" to make sure I can see on the console what page is currently tested.

/**
 * @Then /^I should access all pages of site map "([^"]*)"$/
 */
public function iShouldAccessAllPagesOfSiteMap($selector) {

    $page = $this->getSession()->getPage();
    $locator = sprintf('#%s a', $selector);
    $elements = $page->findAll('css', $locator);

    $steps = array();
    foreach ($elements as $element) {
        /** @var \Behat\Mink\Element\NodeElement $element */
        $steps[] = new Behat\Behat\Context\Step\When(sprintf('I print out page "%s"', $element->getAttribute('href')));
        $steps[] = new Behat\Behat\Context\Step\When(sprintf('I go to "%s"', $element->getAttribute('href')));
        $steps[] = new Behat\Behat\Context\Step\Then('the response status code should be 200');
    }
    return $steps;
}

/**
 * @When /^I print out page "([^"]*)"$/
 */
public function iPrintOutThePage($page) {
    $string = sprintf('Visiting page ' . $page);
    echo "\033[36m    ->  " . strtr($string, array("\n" => "\n|  ")) . "\033[0m\n";
}

Then my scenario looks as follows:

Scenario: my website has no "dead" pages
Given I am on "/examples/site-map/"
Then I should access all pages of site map "c118"

The whole Gist is here https://gist.github.com/fudriot/6028678

like image 29
Fabien Avatar answered Dec 11 '22 09:12

Fabien