Skip to content

Instantly share code, notes, and snippets.

@jcieslar
Created March 19, 2015 16:33
Show Gist options
  • Save jcieslar/6491810f4fd9fada0ab3 to your computer and use it in GitHub Desktop.
Save jcieslar/6491810f4fd9fada0ab3 to your computer and use it in GitHub Desktop.
Capybara and selectize
page.execute_script("$('.selectize-input input').val('ber')")
sleep 0.5
page.execute_script("$('.selectize-input input').keyup()")
sleep 0.5
page.execute_script("$('.full-name').mousedown()")
# https://github.com/brianreavis/selectize.js/blob/master/src/selectize.js
@bunnymatic
Copy link

Here's yet another version of the same. I recently did some shuffling of code such that jQuery was not in the global namespace. Instead it's imported as needed. So my test helpers no longer had access to jQuery. This moves the helper code to using vanilla with querySelector{All} instead of the jquery finder helpers.

module SelectizeSelectHelper
  delegate :execute_script, to: :page

  def find_selectized_control_js(key)
    %{ document.querySelector('##{key}.selectized').nextElementSibling }
  end

  def open_selectize_chooser(key)
    execute_script %{ document.querySelector('##{key}').selectize.open(); }
  end

  def close_selectize_chooser(key)
    execute_script %{ document.querySelector('##{key}').selectize.close(); }
  end

  # Select a single item from a selectized select input where multiple=false given the id for base field
  def selectize_single_select(key, value)
    # It may be tempting to combine these into one execute_script, but don't; it will cause failures.
    open_selectize_chooser(key)
    execute_script %{
                   var options = #{find_selectized_control_js(key)}.querySelectorAll('.option');
                   var option = Array.from(options).find((opt) => opt.innerHTML.match(/#{value}/));
                   option.click() }
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment