listloopsbehatmink

How to iterate through all <select> field options in behat / mink


I am testing a product search form. Products may be searched by different parameters (like status, material, wight etc.). When I want to search by status I do the following:

Scenario Outline: search by status
  When I select "<status>" from "search_form_status"
  And I press "Search"
  And I wait for 3 seconds                        // implemented
  And I follow random link from test result table // implemented
  Then I should see "<status>" in the "div#status" element
Examples:
  |status  |
  |enabled |
  |disabled|

And everything is fine. But if I wanted to test the same search for say, productMaterial I'm stuck as product materials are the subject that can be changed at any time (we may need new materials, may edit material names, or delete old unused ones). Add to that the fact that materials will differ on testing environment and on production site. I know that I can do something like:

Given I select product material

And implement the step with foreach loop like this:

$matList = $this->getSession()->getPage()->findAll('css', "select option");
    foreach($matList as $material){
        // DO SOMETHING
    }
}

But how would I create all the other steps like in the status example? I imagine that I would want to use a $material variable in the following steps in my search.feature file for the steps that follow that custom step. But how do I do that? How would I iterate through all of the options list and do a bunch of steps in each iteration?


Solution

  • You'll need to write the PHP code that runs the individual steps that you want, inside your method that contains the code to select all the options.

    For example:

    $handler = $this->getSession()->getSelectorsHandler();
    
    $optionElements = $this->getSession()->getPage()->findAll('named', array('option', $handler->selectorToXpath('css', 'select ));
    
    foreach ($optionElements as $optionElement) {
        $this->getSession()->getPage()->selectFieldOption('portal', $optionElement->getValue());
        $this->pressButton("show");
        $this->assertPageContainsText(" - Report Report");
    }