Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capybara and Select2 Version 4

How can I fill in/select a select2 search box (gets results via ajax) with capybara.

Using the latest version 4 of select2 and latest capybara/rspec in a rails project.

There are many examples on SO and elsewhere on how to use Capybara with Select2 3.x but not version 4 which is a rewrite.

like image 880
robzolkos Avatar asked Feb 27 '15 09:02

robzolkos


2 Answers

For 4.0, it looks like they actually simplified quite a bit. For a single select, you can just include this helper method:

def select2(value, **options)
  first("#select2-#{options[:from]}-container").click
  find(".select2-results__option", text: value).click
end

Works for me so far, but I haven't tried with more customized versions of the selector yet.

like image 106
Josh Kovach Avatar answered Oct 11 '22 11:10

Josh Kovach


There is capybara-select-2 gem which supports version 2/3/4 of select2. It expects select2 version 4 by default. You can configure it for other version if you use select2 version 2 or 3

Just add the gem to the test group in your Gemfile

group :test do
  gem 'capybara-select-2'
end

Now you can use select2 test helper in Cucumber or RSpec:

select2 'Buy Milk', css: '#todo'

# Search options
select2 'Buy Milk', from: 'Things to do', search: true

# Create new options
select2 'Millennials', from: 'Generations', tag: true

UPDATE: Starting from version 0.3.0 CapybaraSelect2 detects select2 version automatically

like image 3
Hirurg103 Avatar answered Oct 11 '22 10:10

Hirurg103