require 'active_support/concern' module Softwear::Lib module Spec extend ActiveSupport::Concern module CapybaraHelpers def wait_for_ajax begin Timeout.timeout(Capybara.default_wait_time) do wait_for_jquery loop until finished_all_ajax_requests? end rescue sleep 0.1 end end def finished_all_ajax_requests? page.evaluate_script('jQuery.active').zero? end def wait_for_redirect original_url = current_path until current_path != original_url sleep(0.1) end end def wait_for_jquery until page.evaluate_script('jQuery.active') == 0 sleep(0.1) end end def accept_alert page.evaluate_script('window.confirm = function() { return true; }') yield end def dismiss_alert page.evaluate_script('window.confirm = function() { return false; }') yield # Restore existing default page.evaluate_script('window.confirm = function() { return true; }') end end module Select2 def set_select2_field(field, value) page.execute_script %Q{$('#{field}').select2('val', '#{value}')} end def select2_search(value, options) label = find_label_by_text(options[:from]) within label.first(:xpath,'.//..') do options[:from] = "##{find('.select2-container')['id']}" end targetted_select2_search(value, options) end def targetted_select2_search(value, options) page.execute_script %Q{$('#{options[:from]}').select2('open')} page.execute_script "$('#{options[:dropdown_css]} input.select2-input').val('#{value}').trigger('keyup-change');" select_select2_result(value) end def select2(value, options) label = find_label_by_text(options[:from]) within label.first(:xpath,'.//..') do options[:from] = "##{find('.select2-container')['id']}" end targetted_select2(value, options) end def select2_no_label value, options={} raise "Must pass a hash containing 'from'" if not options.is_a?(Hash) or not options.has_key?(:from) placeholder = options[:from] # TODO: still need this? # minlength = options[:minlength] || 4 click_link placeholder select_select2_result(value) end def targetted_select2(value, options) # find select2 element and click it find(options[:from]).find('a').click select_select2_result(value) end def select_select2_result(value) # results are in a div appended to the end of the document within(:xpath, '//body') do page.find('div.select2-result-label', text: %r{#{Regexp.escape(value)}}i).click end end end included do include Warden::Test::Helpers Warden.test_mode! RSpec.configure do |config| config.include CapybaraHelpers, type: :feature config.include Select2, type: :feature end end end end