Matthew Boston

Mixpanel mock

March 12, 2014

tl;dr

A tiny CoffeeScript MixpanelMock class stands in for the real mixpanel object and logs each track call to the console. A Rails layout loads the real library only in production and the mock everywhere else.

Key takeaway: Keep analytics events out of development and QA by loading a console-logging mock outside production.

The mock

When using Mixpanel it’s best not to send events while in development, staging, demo, or QA environments. I created a class to load a mock that will simply log to the console for tracking events.

class MixpanelMock
  track: () ->
      console.log("mixpanel.track", arguments)

window.mixpanel = new MixpanelMock()

Using in Rails

I usually save the Mixpanel JavaScript Library to a file in vendor/assets/javascripts/mixpanel.js.

Then I place MixpanelMock in vendor/assets/javascripts/mixpanel-mock.coffee.

I use the code below to conditionally load the real or fake Mixpanel library.

- if Rails.env.production?
  = javascript_include_tag "mixpanel"
- else
  = javascript_include_tag "mixpanel-mock"

This way, when not in production, all of your Mixpanel tracking events will simply be printed to the console. This also makes it super simple, as a developer, to know when certain events are being sent to Mixpanel.