How to test google analytics (garb) API with Rspec?

99封情书 提交于 2019-12-22 12:37:59

问题


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.


回答1:


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.




回答2:


I would suggest creating a testing interface that mimicks the actual calls to the google API. The other option would be to use mocks to create sample data.

I agree that it's best to not hit the actual API, since this does not gain you anything. A call to the actual API might succeed one day and fail the next because the API owners change the response format. Since GA probably won't change it's versioned API I think it's safe to create an interface that you can use in your test environments for faster testing.



来源:https://stackoverflow.com/questions/4832106/how-to-test-google-analytics-garb-api-with-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!