How to test a Select2 element with capybara DSL?

sbeam picture sbeam · Oct 7, 2012 · Viewed 9.6k times · Source

I have a Select2 element on a page that loads results via ajax. Would like to test this with capybara/rspec (using the poltergeist driver), but since the Select2 element actually starts out as a hidden field, and then populates a <ul> once results are processed, none of the normal select, fill_in or choose helpers will work.

What I have now is something like

  it "should have a search field for events" do
    click_link "Select an Event"       # this works as expected
    within('.select2-container') do    # works
      find('.select2-search input').set(event.description[0,5])  # won't work!
      find(:xpath, "li[text()='#{event.description}']").click 
    end
    click_button "Search"
    page.should have_content("Displaying all 2 photos")
  end

line 4 above, apparently capybara can find the element but the value isn't changed and Select2 never makes its ajax call. (can't use normal fill_in there because the search field element has no label, id, or name attributes)

Answer

Huzaifa Saifuddin picture Huzaifa Saifuddin · Apr 13, 2016

Stop scratching your head, do this and it will work

select "option_name_here", :from => "Id Of Your select field"

I tried every module and every damn thing I could and finally just did this without any helper and such things by a simple line of code.