Search code examples
rubyajaxcapybaraphantomjspoltergeist

how to test / interact with AJAX autocomplete and Capybara / Poltergeist


I am trying to interact with an external website at: http://is.gd/LtgYEk I need to be able to fill in the input with id="textOrigen" here is the html

<p>
    <label class="form-label">Departing from:</label>
    <span class="label-field">
        <input type="text" autocomplete="off" onblur="onblur2('textOrigen');" onfocus="initID('textOrigen');" size="17" id="textOrigen" name="text" maxlength="40" style="position:static;color: #505050;">
        <select style="display:none" onchange="clearValidate(); Origen();" class="validate[dynamic]" id="cmbOrigen" name="cmbOrigen">
            <option value="-1" selected="selected">Origin</option>
        </select>
        <label class="label-error" id="lblerrorOrigen"></label> 
    </span>
</p>

I put together a simple ruby script using 'capybara/poltergeist'

I am unable to replicate the browser behavior, which is: on click the input field default value is highlighted thus being deleted as you start typing.

I lost track of all different variations I tried, but tried many. I found another SO post which seemed somewhat useful but it didn't help

This is the last revision of the method to fill this field:

def session.fill_autocomplete(field, options = {})
  execute_script %Q{ $('##{field}').trigger('focus') }
  fill_in field, with: options[:with]
  execute_script %Q{ $('##{field}').trigger('focus') }
  execute_script %Q{ $('##{field}').trigger('keydown') }
  selector = %Q{#output div:contains('#{options[:with]}')}
  execute_script "$(\"#{selector}\").mouseenter().click()"
end

As I wrote the script is very simple, the only other relevant bit is when the session is instantiated with:

session = Capybara::Session.new(:poltergeist)

Any help would be greatly appreciated.


Solution

  • I found the solution after testing in many ways. The key was to add some delay to allow the auto suggest div to be populated.

    Here is the method that worked:

    def session.fill_city(field, options = {})
      sleep 3
      script = %Q{ $("#{field}").focus().keypress().val("#{options[:with]}") }
      execute_script(script)
      sleep 2
      find('#output').find('div').trigger('click')
    end