markwalker_
markwalker_

Reputation: 12859

Checking for a field error using Selenium Webdriver

I've been trying to implement tests to check for field validation in forms. A check for specific field error messages was straightforward, but I've also tried a generic check to identify the parent element of a field for an error class. This however isn't working.

A field with an error has the following HTML;

<div class="field clearfix error ">
    <div class="error">
        <p>Please enter a value</p>
    </div>
    <label for="id_fromDate">
    <input id="id_fromDate" type="text" value="" name="fromDate">
</div>

So to check for an error I've got the following function;

def assertValidationFail(self, field_id):
    # Checks for a div.error sibling element
    el = self.find(field_id)
    try:
        error_el = el.find_element_by_xpath('../div[@class="error"]')
    except NoSuchElementException:
        error_el = None
    self.assertIsNotNone(error_el)

So el is the input field, but then the xpath always fails. I believed that ../ went up a level in the same way that command line navigation does - is this not the case?

Upvotes: 0

Views: 2357

Answers (2)

Vince Bowdren
Vince Bowdren

Reputation: 9208

When you're using a relative xpath (based on an existing element), it needs to start with ./ like this:

el.find_element_by_xpath('./../div[@class="error"]')

Only after the ./ can you start specifying xpath nodes etc.

Upvotes: 1

Yi Zeng
Yi Zeng

Reputation: 32865

Misunderstood your question earlier. You may try the following logic: find the parent div, then check if it contains class error, rather than find parent div.error and check NoSuchElementException.

Because .. is the way to go upper level, ../div means parent's children div.

// non-working code, only the logic
parent_div = el.find_element_by_xpath("..") # the parent div
self.assertTrue("error" in parent_div.get_attribute("class"))

Upvotes: 1

Related Questions