Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a Select2 element with capybara DSL?

Tags:

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)

like image 379
sbeam Avatar asked Oct 07 '12 18:10

sbeam


2 Answers

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.

like image 178
Huzaifa Saifuddin Avatar answered Oct 01 '22 17:10

Huzaifa Saifuddin


I created a helper that you can use with Cucumber, it doesn't have a sleep so it's faster than the methods above. This also works if you use the createSearchChoice provided by Select2.

Put it in features/support/select2_helper.rb

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) 

Use it like this:

Then(/^I select2 "([^"]*)" from "([^"]*)"$/) do |value, select_name|   select2 value, from: select_name end 

Tested with Rails 4.1.1 and Cucumber 1.3.15.

like image 42
Jankeesvw Avatar answered Oct 01 '22 18:10

Jankeesvw