Iterate through all form fields with selenium in ruby
I am trying to validate that my form fields all have an associated label using Selenium, but I am having problems grabbing all of the form fields on a page. get_all_fields only gets textfields; I have no way to also grab the passwords, radios, checkboxes, etc.
I was trying something like this:
num_fields = Integer(sele开发者_开发技巧nium.get_xpath_count("//input"))
1.upto(num_fields) do |field_number|
input_id = selenium.get_attribute("//input[#{field_number}]@id")
selenium.element?("css=label[for=#{input_id}]")
end
The problem is that //input[1] doesn't work; the inputs are nested in various markup depending on the page.
Is there a way to use a selenium locator to generically grab the first, second, etc input?
Try using //body/descendant::input[#{field_number}]
.
Learning a bit about how XPath works will help with this sort of testing; Dave Hunt's suggestion of //body/descendant::input[#{field_number}]
is pretty good; the descendant::input
part will return an array that the field_number will index into.
There are other XPath axes that will also give arrays - you may also want to use the form element as the start of the descendants rather than body.
The only downside is that the xpath expression will get evaluated each time around the loop. If you have a lot of input controls, or a slow browser like IE, this may take a comparatively long time - especially if you have other standard checks to make. You may be better off using selenium.get_html_source
and developing a WebStandardsChecker
class to evaluate the page in a single pass.
精彩评论