Created
February 5, 2009 17:59
-
-
Save nakajima/58876 to your computer and use it in GitHub Desktop.
Run Javascript with Selenium. Easily.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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