Skip to content

Instantly share code, notes, and snippets.

@onyxrev
Created October 14, 2013 04:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onyxrev/6970632 to your computer and use it in GitHub Desktop.
Save onyxrev/6970632 to your computer and use it in GitHub Desktop.
Select2 search query and selection for Capybara
# usage:
# select2_choose("#some_element_id_with_select2_attached", :query => "Santa", :choose => "Santa Monica, California")
# NOTE: just make sure your 'choose' is unique in your results set
module Select2Helper
def select2_choose(id, options)
page.execute_script %Q{
i = $('#s2id_#{id} .select2-offscreen');
i.trigger('keydown').val('#{options[:query]}').trigger('keyup');
}
within(".select2-drop-active") do
find(".select2-result-label", :text => options[:choose]).click
end
end
end
Copy link

ghost commented Oct 16, 2013

Hi! I'm getting the error:

Capybara::NotSupportedByDriverError:
       Capybara::Driver::Base#execute_script
     # ./spec/features/city_spec.rb:95:in `select2_choose'
     # ./spec/features/city_spec.rb:87:in `fill_licenciated_form'
     # ./spec/features/city.rb:31:in `block (2 levels) in <top (required)>'

This code have some gem dependency?

@geordee
Copy link

geordee commented Feb 5, 2014

I got it working a bit differently. In my case there are multiple Select2 fields and all those had class "select2-drop-active", and the find was failing. Moreover, I wanted to have an approximate match, to make the specs a bit more easier.

Here is what I have come up with.

module Select2Helper
  def select2_choose(id, options)
    options[:query] ||= options[:choose]

    page.execute_script %Q{
      $('#s2id_#{id} .select2-offscreen')
        .trigger('keydown')
        .val('#{options[:query]}')
        .trigger('keyup');
    }

    if options[:first]
      find(".select2-highlighted .select2-match").click
    else
      find(".select2-result-label", text: options[:choose]).click
    end
  end
end

@MariaFamador
Copy link

I' m also getting the same error as above when using either of the solutions.

Capybara::NotSupportedByDriverError:
Capybara::Driver::Base#execute_script

@Valve
Copy link

Valve commented May 15, 2014

@MariaFamador, make sure you have a js enabled driver, for example phantomjs.

@senott
Copy link

senott commented May 13, 2015

I'm getting "Circular dependency detected while autoloading constant Admin::Select2Helper (RuntimeError)" with either of the solutions.

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