Search code examples
phpiframeselenium-webdriverbehatmink

Behat with Mink extension and selenium2 to automate a test case


I am trying to select an iFrame which has a text box within it. Here is the structure of the page:

<html>
<body>
<many text fields>
<iframe>
#document
<html>
<body>
<p>
WRITE TEXT HERE;
</p>
</body>
</html>
</iframe>
<more tags to do other things>
</body>
</html>

And here is my function to access and write text in the

tags within the tags:

// Select iFrame
/**
 * 
 *
 * @Given /^I switch to iframe "([^"]*)"$/
 */
public function iSwitchToIframe($field1)
{
    $field1 = $this->fixStepArgument($field1);
    $page = $this->getSession()->getPage();
    $el = $page->find('css', $field1);
    $this->fillField($el, 'This is field value');
}

I am not sure what am I doing wrong here. I keep getting 'Object of class NodeElement could not be converted to a string' error.


Solution

  • fillField() accepts two arguments:

    • locator - input id, name or label (string)
    • value (string)

    The find() method returns a NodeElement, so you cannot pass it to fillField().

    You could call setValue() on the field:

    $field1 = $this->fixStepArgument($field1);
    $page = $this->getSession()->getPage();
    $formElement = $page->find('css', $field1);
    if (null === $formElement) {
        throw new \LogicException(sprintf('Form field not found: "%s"', $field1));
    }
    $formElement->setValue('a value');
    

    However, it looks like you're passing a css selector from your scenario. It would be better if you passed a meaningful name, and converted it to a css selector or an id in the context file:

    // you'll need to covert a name that came from the scenario to a selector
    // you could also use a label
    $selector = $this->convertFieldNameToIdOrNameOrLabel($field1);
    $this->fillField($selector, 'This is field value');
    

    By putting css selectors into your scenarios you're polluting them with technical details. If you prefer to follow this practice, you'd be better off using mink directly with no Behat (since you're not really doing acceptance testing, but simply functional testing).