Skip to content

Instantly share code, notes, and snippets.

@whatcould
Forked from joshuaclayton/README.md
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whatcould/82b604b791bd7ee192cf to your computer and use it in GitHub Desktop.
Save whatcould/82b604b791bd7ee192cf to your computer and use it in GitHub Desktop.
RSpec custom matchers for Segment.io tracking
RSpec::Matchers.define :have_tracked do |event_name|
match do |backend|
@event_name = event_name
@backend = backend
if @match_user && @properties
backend.tracked_events_for(@match_user).named(@event_name).has_properties?(@properties)
elsif @properties
backend.tracked_events.named(@event_name).has_properties?(@properties)
elsif @match_user
backend.tracked_events_for(@match_user).named(@event_name).events.any?
else
backend.tracked_events.named(@event_name).events.any?
end
end
description do
"tracked event"
end
failure_message_for_should do |text|
"expected event '#{@event_name}' to be tracked for user '#{@match_user}' with included properties #{@properties} but was not"
end
failure_message_for_should_not do |text|
"expected event '#{@event_name}' not to be tracked for user '#{@match_user}' with included properties #{@properties} but was"
end
chain(:for_user) { |user| @match_user = user }
chain(:with_properties) { |properties| @properties = properties }
end
RSpec::Matchers.define :have_identified do |user|
match do |backend|
@match_user = user
@backend = backend
@traits ||= {}
backend.has_identified?(@match_user, @traits)
end
description do
"identified user"
end
failure_message_for_should do |text|
"expected identification of user '#{@match_user}' with traits #{@traits}, who was not"
end
failure_message_for_should_not do |text|
"expected no identification of user '#{@match_user}' with traits #{@traits}, who was"
end
chain(:with_traits) { |traits| @traits = traits }
end
@whatcould
Copy link
Author

This version allows leaving out parts of the have_tracked (like users and properties); you can call have_tracked('event name') and it will still pass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment