Skip to content

Instantly share code, notes, and snippets.

@nakajima
Created February 5, 2009 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nakajima/58876 to your computer and use it in GitHub Desktop.
Save nakajima/58876 to your computer and use it in GitHub Desktop.
Run Javascript with Selenium. Easily.
module SeleniumHelpers
# Execute JavaScript in the context of your Selenium window
def run_javascript(javascript)
driver.get_eval <<-JS
(function() {
with(this) {
#{javascript}
}
}).call(selenium.browserbot.getCurrentWindow());
JS
end
private
# If running in regular Selenium context, get_eval is defined on self.
def driver
respond_to?(:selenium) ? send(:selenium) : self
end
end
class JavaScriptHelperTest < ActiveSupport::TestCase
include SeleniumHelpers
include ElementHelpers
def setup
@element = locate('#all')
end
def test_visible_by_default
assert @element.visible?
end
def test_hide_element
@element.hide!
assert ! @element.visible?
end
def test_show_element
@element.hide! # setup
@element.show!
assert @element.visible?
end
end
module ElementHelpers
class Element
def initialize(context, selector)
@context, @selector = context, selector
end
def hide!
call(:hide)
end
def show!
call(:show)
end
def visible?
call(:is, ':visible') == 'true'
end
private
def call(fn, *args)
@context.run_javascript <<-JS
return jQuery(#{@selector.inspect})[#{fn.to_s.inspect}](#{args.map(&:inspect).join(', ')});
JS
end
end
def locate(selector)
Element.new(self, selector)
end
end
When /^I click "(.*)"$/ do |text|
run_javascript <<-JS
jQuery('*:contains("#{text}")').click();
JS
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment