Integration tests for keyboard accelerators
I'm using a combination of rspec + capybara + poltergeist to test a Rails 3 app. Since the app has a lot of UI elements, it's important to test the keyboard accelerators.
The problem is most of the test frameworks don't have a way to natively simulate keystrokes, so I wrote sendkey
to do that for me. Throw this into a module and include it in your spec_helper, or anywhere that suits your style:
def sendkey(target, keycode, *meta)
script = "var e=jQuery.Event('key#{meta.empty? ? 'press' : 'down'}');"
script += "e.metaKey=true;" if meta.include? 'command'
script += "e.altKey=true;" if meta.include? 'alt'
script += "e.keyCode=#{keycode};$('#{target}').trigger(e);"
page.driver.execute_script(script)
end
This function builds up a javascript script and sends it to the page for execution. If you're using selenium instead of poltergeist, the last line should be:
page.driver.browser.execute_script(script)
Call it from your spec with the css selector for the target element and the key you want to send. sendkey('body', 13)
sends an enter key to the body element, for instance.
Add 'command' and/or 'option' to the argument list if you want to send an apple/windows or alt/option key respectively. sendkey('body', 13, 'command', 'option')
sends option+apple+return (alt+windows+enter in PC-lingo).