Ruby Selenium ActionBuilder send_keys method duplicating the strings I send

1k Views Asked by At

So let say I have an array called list that contains strings per below, when I loop through the array to send_keys each items from the array onto an online text editor element which already has focus:

list = ["First", "Second", "Third"]

for index in 0 ... list.size
      line = list[index]
      chain.send_keys(line).perform
      if index < list.size 
        page.driver.browser.action.send_keys(:return).perform
      end
end

The problem I'm facing is that instead of the output to look like this:

First

Second

Third

it instead looks like this:

First

First Second

First Second Third

Why is this happening ? is it because the previous actions are still in the action queue and have not cleared up ? or some other reason ? I'd appreciate if anyone can help.

2

There are 2 best solutions below

1
On BEST ANSWER

When using the actions api it builds up a list of actions that are then executed by calling perform. Calling perform however doesn't reset that list, so if you call perform again it repeats the same actions. With the way you're calling it

chain.send_keys(line).perform

adds a send_keys action to chain - then performs it. Next time it adds another send_keys action to chain and then performs both actions. Solutions for that would be just create a new action chain each time rather than reusing chain or calling chain.clear_actions to clear the action chain each time through the loop.

What isn't clear though is why you're using the action API at all rather than just calling send_keys on the element you want to send the keys too

el = find(...)  # find the element on the page you want to send the keys to
list.each do { |str| el.send_keys(str, :return) }
3
On

The way selenium sendkeys works is, the sendkeys commands sends the string value to the text element, It will not do any check whether is there any text present in it or not. If you want to have the keys set newly for each time, Please use the command chain.clear() before chain.send_keys(line).perform in the loop. This will ensure the text in the element is cleared each time before the send_keys.

Let me know if this doesn't help you.

https://selenium-python.readthedocs.io/navigating.html#interacting-with-the-page