We're hiring!

We're actively seeking developers & designers for our new Detroit location. Learn more

Some useful selenium helpers

Wouldn’t it be nice if you could evaluate arbitrary javascript in the context of your Rails application’s window when testing it with Selenium? Well, you already can. What Selenium doesn’t do for you, however, is automatically serialize the result of your computation to JSON, then deserialize that JSON into a convenient ruby object. What I want to do is stuff like this:

1
2
3
# get the center of the page's google map 
lat, lng = get_json "[c.lat(), c.lng()]",
        :c => "googleMap.getCenter()"

or

1
2
positions = get_json "{foo: $('foo').offsetLeft, bar: $('bar').offsetLeft}"
assert positions['foo'] < positions['bar'], "bar was too far to the right"

Here’s the definition of get_json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
   # evaluate arbitrary javascript in the context of your page. 
   def eval_js(code)
     get_eval <<-JS
       selenium.browserbot.getCurrentWindow().eval("#{
         code.gsub('"', '\\\\"').gsub("\\n"," ")
       }") 
     JS
   end

   def get_json(code, objects={})
     entries = objects.entries
     ActiveSupport::JSON.decode(
       eval_js("
         Object.toJSON(
           (function(#{entries.map (&:first).join(', ')}){
             return #{code};
           })(#{entries.map(&:last).join(', ')})
         )
       ")
     )
   end
This entry was posted in Languages, Tools and tagged . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">