Skip to content

Instantly share code, notes, and snippets.

@artem-mindrov
Last active December 15, 2015 10:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artem-mindrov/5248796 to your computer and use it in GitHub Desktop.
Save artem-mindrov/5248796 to your computer and use it in GitHub Desktop.
Helper for testing jquery tokeninput with Selenium & Capybara
class TagsController < ApplicationController
before_filter :authenticate_user!
respond_to :json
def index
q = params[:tag]
if q =~ %r{,|;}
q.gsub!(%r{(,|;).*}, "")
ActsAsTaggableOn::Tag.find_or_create_by_name(q)
end
@tags = ActsAsTaggableOn::Tag.named_like(q).limit(10)
response = @tags.map { |t| { id: t.name, name: t.name } }
render json: response
end
end
module TokenInputHelpers
def fill_in_token_input(locator, options)
raise "Must pass a hash containing 'with'" unless options.is_a?(Hash) && options.has_key?(:with)
field = _find_fillable_field(locator)
ti = _find_fillable_field("token-input-#{field[:id]}").native
ti.clear
options[:with].split(", ").each do |item|
set_token_input(ti, item)
xpath = "//*[contains(@class, 'token-input-dropdown')]//li[contains(normalize-space(string()), '#{item}')]"
begin
find(:xpath, xpath).click
rescue Capybara::ElementNotFound # if nothing was found, try appending a semicolon to trigger tag creation, see controller code below
set_token_input(ti, ";")
find(:xpath, xpath).click
end
end
end
def set_token_input(input, text)
input.send_keys(text)
rescue
page.driver.browser.execute_script %Q{
var msg = '#{text}';
$('##{input[:id]}').val(msg);
var kp = jQuery.Event('keydown');
kp.ctrlKey = false;
kp.which = msg.charCodeAt(0);
kp.keyCode = msg.charCodeAt(0);
$('##{input[:id]}').trigger(kp);
}
end
protected
def _find_fillable_field(locator)
find(:xpath, XPath::HTML.fillable_field(locator))
end
end
World(RegistrationHelpers, InputHelpers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment