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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With