Search code examples
ruby-on-railscapybarajquery-select2-4

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.


Solution

  • 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