Skip to content

Instantly share code, notes, and snippets.

@phoenixwizard
Forked from michael-harrison/test_multi_select.rb
Created December 4, 2013 13:29
Show Gist options
  • Save phoenixwizard/7787418 to your computer and use it in GitHub Desktop.
Save phoenixwizard/7787418 to your computer and use it in GitHub Desktop.
=begin
Notes
=====
Labels: On the label you should put a "for" attribute if you're not using something like simple_form
This helps capybara to find your field
e.g. <label for="my_field_id">Some label</label>
=end
field = "Label on my field"
value = "existing option in list"
# Find the field
field = find_field(field_name)
# Open the Chosen drop down
page.execute_script(%Q!$("##{field[:id]}_chzn").mousedown()!)
# Simulate text being typed
typed_text = ""
value.chars.each do |char|
typed_text += char
# Put a value in the search field
page.execute_script(%Q!$("##{field[:id]}_chzn input").val("#{typed_text}")!)
# Fire the search via a keyup
page.execute_script(%Q!$("##{field[:id]}_chzn input").keyup()!)
end
# Do the selection via firing a keyup on the Enter key when you have the exact text for the option
page.execute_script(%Q!$("##{field[:id]}_chzn input").trigger(jQuery.Event("keyup", { keyCode: $.ui.keyCode.ENTER }))!)
# OR
# Do the selection via firing a mouse up on the option when you have partial text for the option
page.execute_script(%Q!$("##{field[:id]}_chzn .chzn-results li:contains('#{value}')").mouseup()!)
=begin
Notes
=====
Labels: On the label you should put a "for" attribute if you're not using something like simple_form
This helps capybara to find your field
e.g. <label for="my_field_id">Some label</label>
=end
field = "Label on my field"
value = "partial text for an existing option in list"
# Find the field
field = find_field(field_name)
# Open the Chosen drop down
page.execute_script(%Q!$("##{field[:id]}_chzn").mousedown()!)
# Simulate text being typed
typed_text = ""
value.chars.each do |char|
typed_text += char
# Put a value in the search field
page.execute_script(%Q!$("##{field[:id]}_chzn input").val("#{typed_text}")!)
# Fire the search via a keyup
page.execute_script(%Q!$("##{field[:id]}_chzn input").keyup()!)
end
# If you're using Ajax Chosen then wait for the Ajax callback
sleep 1
start_time = Time.now
page.evaluate_script('jQuery.isReady&&jQuery.active==0').class.should_not eql(String) until page.evaluate_script('jQuery.isReady&&jQuery.active==0') or (start_time + 5.seconds) < Time.now do
sleep 1
end
# Do the selection via firing a mouse up on the option
page.execute_script(%Q!$("##{field[:id]}_chzn .chzn-results li:contains('#{value}')").mouseup()!)
# Check that the selection has been made
# Webkit
select_option_text = find_field(field_name).find("option[@value='#{selected_value}']").text
# Selenium
select_option_text = find_field(field_name).find("option[@value='#{selected_value}']")[:text]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment