Test embedded Google Maps coordinates with RSpec and Capybara

So it’s easy to test the coordinates you should be sending to the map you’re about to embed. What if you want to check the coordinates the map is actually embedding? The following will let you do just that.

See the disclaimer regarding test brittleness and overall thoughts.

The code

After including any necessary login methods and creating the location we’re testing, we want to make sure there is a map element.

expect(page).to have_css('div#location_map_canvas')

Next, Google adds two links to their embedded maps. I believe one sends you to a static version, and the other is a link to report errors. We’ll use this link to extract the coordinates.

mapCoordinateString = page.first('div#location_map_canvas').first('a')['href']

We then extract the coordinates and check them against the coordinates that should have been loaded. Note the allowance for differing float precision.

targetCoordinates = Rack::Utils.parse_query URI(mapCoordinateString).query  
splitString = targetCoordinates['ll'].split(',')

# check loaded coordinates
expect(splitString[0].to_f).to be_within(0.1).of(location.latitude)
expect(splitString[1].to_f).to be_within(0.1).of(location.longitude)

And that’s that! We’ve tested the coordinates used to embed the map. Included below is the full example:

# spec/features/locations_spec.rb

feature 'Locations' do

background do
# add your login methods here
end

scenario 'render an existing location', :js => true do
location = create(:location, user: user)
visit location_path(location)

# check for map element
expect(page).to have_css('div#location_map_canvas')

# get a help link from the map canvas that contains the latitude and longitude
mapCoordinateString = page.first('div#location_map_canvas').first('a')['href']

targetCoordinates = Rack::Utils.parse_query URI(mapCoordinateString).query
splitString = targetCoordinates['ll'].split(',')

# check loaded coordinates
expect(splitString[0].to_f).to be_within(0.1).of(location.latitude)
expect(splitString[1].to_f).to be_within(0.1).of(location.longitude)
end
end

Disclaimer

Overall, this is quite a brittle test. Google could easily change their embed structure, causing the test to fail.

In addition, I’m not entirely sure of the usefulness of testing the embed coordinates this way. If you’re supplying the proper coordinates to Google in the first place, there’s not a whole lot that can be done to fix things if they return the wrong coordinates in the embedded map. In the end, I was more interested in trying this for myself, learning a bit more about RSpec (and some Capybara) along the way, and seeing if it were possible.


Originally published at danahartweg.com on March 3, 2014.