JavaScript Integration Testing Example: Installing And Using Mixpanel

We’ve been on a
quest
for years to make sure our integration tests cover the JavaScript components of
the app. Here’s an example: installing Mixpanel in
Copycopter to track visits, user sign ups, user
activity during the free trial, and subscriptions.

Gemfile:

gem'capybara-webkit'

features/support/env.rb:

Capybara.javascript_driver=:webkit

features/mixpanel.feature:

Background:Given the following plan exists:|id|name|price|trial||16|Supersonic|5|false||5|Trial|0|true|And the following limits exist:|plan|name|value||name:Supersonic|users|13||name:Supersonic|projects|14|@javascriptScenario: Track visitor learning about Copycopter
When I go to the homepage
Then mixpanel should track the "visited-home" event
When I follow "Take a tour"Then mixpanel should track the "clicked-tour" event
When I follow "Next, view plans and pricing"Then mixpanel should track the "clicked-next-to-plans-and-pricing" event
@javascriptScenario: Track visitor signing up for free trial
When I go to the homepage
And I follow "Plans and Pricing"Then mixpanel should track the "clicked-plans-and-pricing" event
When I follow "Choose free trial"Then mixpanel should track the "viewed-plan" event with the properties:|plan_id|5|

We use the @javascript tag, which will use Capybara
Webkit to drive the browser in
these tests.

We explicitly set the id’s of the ActiveRecord objects so we can check that
Mixpanel receives the right plan id’s using their properties
feature.

features/step_definitions/mixpanel_steps.rb:

Then%r{^mixpanel should track the "(.*)" event$}do|event_name|mpq=JSON.parse(evaluate_script(%{JSON.stringify(mpq);}))mpq.shouldinclude(["track",event_name])endThen%r{^mixpanel should track the "(.*)" event with the properties:$}do|event_name,table|mpq=JSON.parse(evaluate_script(%{JSON.stringify(mpq);}))properties=table.transpose.hashes.firstmpq.shouldinclude(["track",event_name,properties])end

This is a little funky. We’re using JSON.stringify via
json2.js and
then Ruby’s JSON.parse to convert Mixpanel’s mpq Javascript object into its
Ruby equivalent in order to invoke expectations on it.

If you enjoyed this post, you might also like:

Want to level up your testing game?
Learn about testing Rails applications and TDD
in our new book
Testing Rails.
The book covers each type of test in depth,
intermediate testing concepts,
and anti-patterns that trip up even intermediate developers.