Becks303 Becks303 - 3 months ago 17
Ruby Question

Clear input field: undefined method `clear' for #<Watir::Input:XYZ> (NoMethodError)

I am not sure why I can not

clear
my input field.

PageObject:

element(:test_input_field) { |b| b.input(class: "search-field") }

def set_search_value(search_entry)
test_input_field.when_present.clear
test_input_field.when_present.set(search_entry)
end


Step_file:

page.set_search_value(search_entry)


Output:

undefined method `clear' for #'<'Watir::Input:0x00000003980d20'>' (NoMethodError)

Answer

The clear (and set) method are not defined for generic input elements - ie Watir::Input. They are only defined for the specific input types - text field, checkbox, etc.

To make the code work, you would need to convert the input into the more specific type, which is likely a text field. You can do this using the to_subtype method:

test_input_field.when_present.to_subtype.clear
test_input_field.when_present.to_subtype.set(search_entry)

As @SaurabhGaur mentions, set already starts by clearing the existing value, so you could just do:

test_input_field.when_present.to_subtype.set(search_entry)

Unless the input type changes, it would make more sense to define the element as a text_field so you do not need to convert it. It might depend on which page object library you are using, but I would expect you could do:

element(:test_input_field) { |b| b.text_field(class: "search-field") }

def set_search_value(search_entry)
  test_input_field.when_present.clear
  test_input_field.when_present.set(search_entry)
end