I have a customized GA integration in order to work more smoothly with turbolinks. (Based loosely on: http://reed.github.io/turbolinks-compatibility/google_analytics.html)
Now like a good little code monkey I want to cover my code in my tests. After much googling I found a surprising dearth of acceptable testing methods. Mostly just a manual make sure the code/tracking pixel is present sort of thing. Which obviously won't work long term; someone will forget to check a page or an interaction type and broken code will ship.
So how can I automatically test that my integration of GA is working correctly? (I'm already using capybara-webkit for integration testing)
There is a version of the GA js that logs all activity to the browser console (ga_debug.js). Capybara-webkit allows you to access the browser console log from the driver which means that you can simply wrap your actions in assert_difference('page.driver.console_messages.select {|m| m[:message] == "Track Pageview" }.length',n) do ... end
and get really slick testability of your code.
There's also a version for universal analytics: https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#debug you just have to adjust your message filter to catch the right messages.
While there are other approaches, such as mocking out GA or setting up a proxy server; they are more work and require me to know what the GA server expects from the GA client code, and update when that changes. This way I don't have to change a thing, just use the correct client library for the job.