Skip to content

Instantly share code, notes, and snippets.

@infertux
Last active July 27, 2024 16:50
Show Gist options
  • Save infertux/5974047 to your computer and use it in GitHub Desktop.
Save infertux/5974047 to your computer and use it in GitHub Desktop.
Helper to select a Select2 item with Capybara/Cucumber
# spec/support/capybara/select2_helper.rb or features/support/select2_helper.rb
module Select2Helper
# @example
# select2 "Item", from: "select_id"
# select2 /^Item/, from: "select_id"
#
# @note Works with Select2 version 3.4.1.
def select2(text, options)
find("#s2id_#{options[:from]}").click
all(".select2-result-label").find do |result|
result.text =~ Regexp.new(text)
end.click
end
end
World(Select2Helper)
@jankeesvw
Copy link

I updated your Gist because it doesn't work if you use the createSearchChoice method in Select2.

module Select2Helper
  def select2(value, attrs)
    first("#s2id_#{attrs[:from]}").click
    find(".select2-input").set(value)
    within ".select2-result" do
      find("span", text: value).click
    end
  end
end

World(Select2Helper)

@Joseph507
Copy link

Joseph507 commented Nov 7, 2016

I updated it again for a project im doing.
Hope it provide help or guidance to anybody that needs it.

module Select2Helper
  def select2(value, attrs)
    find("#select2-#{attrs[:from]}-container").click
    find(".select2-search__field").set(value)
    within ".select2-results" do
      find("li", text: value).click
    end
  end
end
World(Select2Helper)

@bob
Copy link

bob commented Jan 9, 2018

module Select2Helper
  def select2(value, attrs)
    find("#select2-#{attrs[:from]}-container").click

    list = find(:xpath, '//span[@class="select2-results"]', visible: :all)
    list.find("li", text: value).click
  end
end
World(Select2Helper)

@dgmstuart
Copy link

I agree with the other posters. I'm using:

find(".select2-result-label", text: Regexp.new(text)).click

One problem is that if the list of options is fetched from a remote source, it won't be loaded immediately. In that scenario, if we use:

all(..).find { |result| result.text ... }

...that means that capybara won't wait for the results to exist, so that block will return nil.

If instead we use:

find(..., text: ...)

...then we're telling Capybara to wait for an element to exist which contains that text, and to fail if it doesn't exist.

This blog post was very helpful in understanding this: https://www.varvet.com/blog/why-wait_until-was-removed-from-capybara/

@Hirurg103
Copy link

Hirurg103 commented Sep 13, 2018

I wrapped the code which selects options from select2 into a gem capybara-select-2

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