1

Maybe it could help someone. Wrote a simple capybara helper to set values into select2 fields.

See code below.

Ivan Danci
  • 512
  • 5
  • 24
  • 1
    what is your question exactly, do you want to ask something or telling something to people. – Sachin Singh Feb 03 '14 at 14:00
  • It's a great idea to share this, but to fit the SE format, you should refactor this into a question and and answer, both of which you provide. – Peter Alfvin Feb 03 '14 at 15:50
  • Just wanted to share with this piece of code. Thanks for the feedback, refactored into question/answer style – Ivan Danci Feb 04 '14 at 14:44

1 Answers1

4
module Features
  module CapybaraHelpers
    def select2(value, element_selector)
      select2_container = first("#{element_selector}")
      select2_container.find(".select2-choice").click

      find(:xpath, "//body").find("input.select2-input").set(value)
      page.execute_script(%|$("input.select2-input:visible").keyup();|)
      drop_container = ".select2-results"
      find(:xpath, "//body").find("#{drop_container} li", text: value).click
    end
  end
end

Then in your code just call something like select2("apple", "#s2id_fruit_id") and capybara will select "apple" value in select2 field with #s2id_fruit_id id.

Thanks to goodwill with his capybara-select2 gem.

Ivan Danci
  • 512
  • 5
  • 24
  • Thanks! With a little twist, this works on pages with multiple select2 fields and even multi-selects - see my answer to http://stackoverflow.com/a/28970538/441379 – Jeppe Liisberg Mar 10 '15 at 18:06