如何使用Rspec测试Google Analytics(Garb)API? [英] How to test google analytics (garb) API with Rspec?

查看:226
本文介绍了如何使用Rspec测试Google Analytics(Garb)API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用装扮宝石从Google Analytics中提取一些基本统计信息,例如综合浏览量。一切工作正常,但我无法弄清楚测试我的API调用的最佳方式。这是我的Analytics类的一个配对版本:

  class Analytics 
扩展Garb :: Model

指标:综合浏览量
维度:page_path

用户名='用户名'
密码='密码'
WebPropertyId ='XX-XXXXXXX-X'

#使用Google Analytics(分析)开始会话。

Garb :: Session.login(用户名,密码)

#找到正确的网络媒体资源。

Property = Garb :: Management :: Profile.all.detect {| p | p.web_property_id == WebPropertyId}

#返回给定页面的综合浏览量。

def self.pageviews(path)
Analytics.results(Property,:filters => {:page_path.eql =>路径})first.pageviews.to_i
end

#...从Google分析中提取统计信息的其他方法...
end

非常简单。但除了确保常数已经确定之外,我还没有能够写出有效的测试。测试这种类似的最好方法是什么?以下是一些问题:


  • 我不希望在测试中真正遇到API。它很慢,需要互联网连接。

  • 统计信息显然会随时变化,即使在测试时点击API,也很难设置期望值。



我想我想要一个模拟课程?但我从来没有使用过这种模式。任何帮助都会很棒,甚至只是一些链接让我走上正确的道路。

Fakeweb 是一个很好的开始。它可以将您的SUT与网络隔离开来,以便慢速连接不会影响您的测试。



在不了解Garb的情况下很难知道还有什么可说的。很明显,您需要知道从API发送和接收的数据的格式,因此您可以制作适当的模拟/存根。


I'm using the garb gem to pull some basic stats, like pageviews, from Google Analytics. Everything's working correctly but I can't figure out the best way to test my API calls. Here's a paired down version of my Analytics class:

class Analytics
  extend Garb::Model

  metrics :pageviews
  dimensions :page_path

  Username = 'username'
  Password = 'password'
  WebPropertyId = 'XX-XXXXXXX-X'

  # Start a session with google analytics.
  # 
  Garb::Session.login(Username, Password)

  # Find the correct web property.
  # 
  Property = Garb::Management::Profile.all.detect {|p| p.web_property_id == WebPropertyId}

  # Returns the nubmer of pageviews for a given page.
  # 
  def self.pageviews(path)
    Analytics.results(Property, :filters => {:page_path.eql => path}).first.pageviews.to_i
  end

  # ... a bunch of other methods to pull stats from google analytics ...
end

Pretty simple. But beyond ensuring that the constants are set, I haven't been able to write effective tests. What's the best way to test something like this? Here are some of the problems:

  • I'd prefer not to actually hit the API in my tests. It's slow and requires an internet connection.
  • The stats obviously change all the time, making it difficult to set an expectation even if I do hit the API when testing.

I think I want a mock class? But I've never used that pattern before. Any help would be awesome, even just some links to get me on the right path.

解决方案

Fakeweb is a good place to start. It can isolate your SUT from the network so that slow connections don't affect your tests.

It's hard to know what else to say without knowing more about Garb. Obviously you'll need to know the format of the data to be sent and received from the API, so you can make the appropriate mocks/stubs.

这篇关于如何使用Rspec测试Google Analytics(Garb)API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆