Select a radio button with Mink / Behat

Either I am completely blind or I just haven’t found an out-of-box solution for selecting a radio button with Mink / Behat. I have written a simple step definition which does this for me. In order for it to work, you have to have the radio button input element wrapped by a label element. Use the label text as argument:

/**
 * @When /^I check the "([^"]*)" radio button$/
 */
 public function iCheckTheRadioButton($labelText)
     {
     foreach ($this->getMainContext()->getSession()->getPage()->findAll('css', 'label') as $label) {
         if ($labelText === $label->getText() && $label->has('css', 'input[type="radio"]')) {
             $this->getMainContext()->fillField($label->find('css', 'input[type="radio"]')->getAttribute('name'), $label->find('css', 'input[type="radio"]')->getAttribute('value'));
             return;
         }
     }
     throw new \Exception('Radio button not found');
 }

Use it like this inside your feature:

When I check the "Enabled" radio button

2 comments

  1. Andrew Battye · April 30, 2013

    Thanks for that – I was looking for something similar and your post got me going in the right direction. In my test, however, the radio and its label could be anywhere on the page, so I needed a modified approach. I just needed to check a radio with a specific label was present on the page – didn’t need to select it for these tests.

    /**
    * @Then /^I should see a radio button with the label “([^"]*)”$/
    */
    public function iShouldSeeARadioButtonWithTheLabel($labelText)
    {
    $ok = false;
    $page = $this->getSession()->getPage();

    foreach ($page->findAll(‘css’, ‘label’) as $label) {
    if ($label->getText() === $labelText) {
    // label exists
    $for = $label->getAttribute(‘for’);
    // now find element with that id
    $element = $page->findById($for);
    if ($element) {
    // is it a radio?
    $type = $element->getAttribute(‘type’);
    if ($type and $type === ‘radio’) {
    $ok = true;
    }
    }
    }
    }
    assertTrue($ok);
    }