I'm using PHPUnit to test the output of a PHP function that produces HTML option
tags using provided data.
For example, this is a correct output of the function (I added line returns to improve readability on SO):
<option value="0">Choose one ...</option>
<option value="fooID">fooValue</option>
<option value="barID"selected>barValue</option>
<option value="bazID">bazValue</option>
And to test the output, I'm using this assertion:
$this->assertRegExp("/(<option value=\".*\" *(selected)? *>.*<\/option>)+/i", $res);
where $res
is the output string of the tested function.
And it works well. But I would like to also check that selected
is generated in only one option
tag.
How can I do this? Is there a way to count how many times selected
was matched?
Thanks in advance, be kind, it's my first question on SO :-)
Don't use regexes to parse HTML or XML documents. Use a DOM parser:
// create a document object from the HTML string
$doc = new DOMDocument();
$doc->loadHTML($html);
// create a XPath selector
$selector = new DOMXPath($doc);
// select nodes containing the selected attribute
$result = $selector->query('//*[@selected]');
// make assertion
$this->assertEquals(1, $result->length, 'Failed to assert that result contains exactly one selected element');