Testing jQuery Autocomplete using Capybara
Using Selenium + Capybara + jQuery to select an option from an AutoComplete
Have you ever found yourself pulling your hair out at 3:00am, frustrated and challenged beyond all that is humanly possible, because your tests are unable to select any of the options from an AutoComplete?
No?
Lucky you.
But if you have, this quick jQuery snippet, once placed correctly, will hopefully make your late nights of frustration a little bit shorter.
We first find the text field label, “Name”, and fill it in with text that will cause the AutoComplete to show us a list of the result(s) so that we may select one.
fill_in 'Name', :with => 'Jack'
Moving to the next line, the sleep() is necessary so that the AutoComplete has time to load and have what we want selected. The time count may vary.
sleep 3
Lastly, we tell Capybara to run some script:
- look inside the ui-menu-item list item class,
- find the link (denoted by the anchor (a) tag) that has “Jack Russell Software” in it,
- use the .trigger() function to simulate your mouse entering the AutoComplete field (different version of .mouseenter() http://api.jquery.com/mouseenter/), and
click on the selected field.
page.execute_script ” $(‘#{selector}’).trigger("mouseenter").click();”
May your days (and nights) of testing AutoCompletes be fruitful.
Robert Pearce
Jack Russell Software Company