jcn*_*ghm 12 xml testing rest ruby-on-rails
我想在我的Rails站点上测试REST api.使用rails测试框架,最简单/最好的方法是什么?我只是做标准的资源丰富的东西,所以我特别想知道,因为这是如此的标准,如果有任何自动化方法来测试这些东西.
我推出了自己的解决方案,并认为这将有所帮助.我写了一个模块,它使用json,curb和可寻址的 gem将GET,PUT,POST和DELETE请求发送到localhost:3000.它可以请求XML(作为原始问题要求)或json.它将响应主体作为哈希返回.它主要是围绕路缘宝石的包装,我认为它具有可怕的语法.
请注意,我正在自动加载我的api_key.这可以通过传递:api_key => false或破坏使用来禁用api_key => "wrong".您可能希望将其保留或修改它以适合您的身份验证方案.
这是模块:
module ApiTesting
# requres the json, curb, and addressable gems
require "addressable/uri"
def api_call(path, verb, query_hash={}, options={})
options.reverse_merge! :api_key => "abc1234", :format => "xml"
query_hash.reverse_merge!({:api_key => options["api_key"]}) if options[:api_key]
query = to_query_string(query_hash)
full_path = "http://localhost:3000/#{path}.#{options[:format]}?#{query}"
response = case verb
when :get
Curl::Easy.perform(full_path)
when :post
Curl::Easy.http_post("http://localhost:3000/#{path}.#{options[:format]}", query)
when :put
Curl::Easy.http_put(full_path, nil)
when :delete
Curl::Easy.http_delete(full_path)
end
case options[:format]
when "xml"
Hash.from_xml(response.body_str)
when "json"
JSON.parse(response.body_str)
end
end
private
def to_query_string(val)
uri = Addressable::URI.new
uri.query_values = val
uri.query
end
endRun Code Online (Sandbox Code Playgroud)
以下是一些简单的示例:使用GET请求资源属性:
api_call("calls/41", :get)Run Code Online (Sandbox Code Playgroud)
使用POST创建资源:
api_call("people", :post, {:person => {:first => "Robert", :last => "Smith" } })Run Code Online (Sandbox Code Playgroud)
使用PUT更新资源:
api_call("people/21", :put, {:person => { :first => "Bob" } })Run Code Online (Sandbox Code Playgroud)
使用DELETE删除资源:
api_call("calls/41", :delete)Run Code Online (Sandbox Code Playgroud)
关闭api_key的自动插入:
api_call("calls/41", :get, {}, {:api_key => false})Run Code Online (Sandbox Code Playgroud)
使用错误的api_key:
api_call("calls/41", :get, {}, {:api_key => "wrong"})Run Code Online (Sandbox Code Playgroud)
用作json(默认为xml):
api_call("calls/41", :get, {}, {:format => "json"})Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7073 次 |
| 最近记录: |