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