【发布时间】:2016-05-27 18:29:03
【问题描述】:
我正在从事一个从外部 REST API(来自 Facebook、Twitter 或 Instagram 等社交网络)获取数据的项目。
我不确定我所做的是对还是错,所以我需要一些指导。我不知道,当人们创建依赖于外部数据(REST API 或抓取数据)的应用程序时,他们如何使用它进行 TDD。
我的问题是:我正在尝试对调用外部 REST API 的方法进行 TDD 测试。这是对还是错?
- 如果正确,如何使用 RSpec 进行测试?有没有我可以阅读的指南或资料来源?
- 如果错误,我该如何检查?如果我将 API_VERSION 更改为更高版本,我怎么知道逻辑仍然运行良好,并且所有必填字段仍然存在?
例如:
我有这样的代码:
API_VERSION = "v2.5"
FIELD_PAGE_GRAPH = %w(id name picture{url} likes cover is_community_page category link website has_added_app
talking_about_count username founded phone mission location is_published description can_post checkins company_overview
general_info parking hours payment_options access_token
)
FIELD_STREAM_GRAPH = %w(id message story comments.summary(true) likes.summary(true).limit(500) from to link shares created_time
updated_time type is_published attachments scheduled_publish_time application
)
def self.get_stat_facebook(page_id,access_token=nil)
graph = Koala::Facebook::API.new(access_token)
graph.get_objects(page_id.to_s,{:fields => FIELD_PAGE_GRAPH}, {:api_version => API_VERSION})
end
def self.get_feed_facebook(page_id,access_token=nil, options = {})
options = options.with_indifferent_access
retry_time = 0
begin
graph = Koala::Facebook::API.new(access_token)
params = {:fields => FIELD_STREAM_GRAPH, :limit => 25}
params.merge!({:since => options[:_since].to_i}) if options[:_since].present?
params.merge!({:until => options[:_until].to_i}) if options[:_until].present?
results = []
loop do
graph_response = graph.get_object(page_id.to_s+"/feed", params, {:api_version => API_VERSION})
break if graph_response.blank?
results = results+graph_response
break if options[:_since].blank?
params[:until] = graph_response.sort_by!{|result| result['created_time']}.first['created_time'].to_time.to_i-1
end
rescue Koala::Facebook::ServerError
sleep 1
retry_time += 1
retry if retry_time <= 3
end
filter_owner_page(results, page_id)
end
然后我有一个类似的规范
require 'spec_helper'
RSpec.describe SocialNetwork do
context ".get_stat_facebook" do
it "when access token is expired"
it "when access token is not expired"
it "when page id is not exist"
it "when page id is exist"
end
context ".get_feed_facebook" do
it "when access token is expired"
it "when access token is not expired"
it "when page id is not exist"
it "when page id is exist"
it "data contain id field"
it "data contain message field"
it "data contain attachment field"
end
end
【问题讨论】:
-
包含
SocialNetwork的类定义会更清楚。
标签: ruby rspec tdd automated-tests koala