ruby-on-rails - 测试 Rails REST XML API 的最佳方式?

标签 ruby-on-rails xml testing rest

我想在我的 Rails 站点上测试 REST api。使用 Rails 测试框架执行此操作的最简单/最佳方法是什么?我只是在做标准的足智多谋的事情,所以我特别想知道,因为这是如此沼泽的标准,是否有任何自动的方法来测试这些东西。

最佳答案

我对此提出了自己的解决方案,并认为它会有所帮助。我写了一个使用 json 的模块, curb , 和 addressable gems 向 localhost:3000 发送 GET、PUT、POST 和 DELETE 请求。它可以请求 XML(如原始问题所要求的那样)或 json。它将响应主体作为哈希返回。它主要是 curb gem 的包装器,我认为它的语法很糟糕。

请注意,我正在自动加载我的 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

end

下面是一些简单的例子: 使用 GET 请求资源属性:

    api_call("calls/41", :get)

使用 POST 创建资源:

    api_call("people", :post, {:person => {:first => "Robert", :last => "Smith" } })

使用 PUT 更新资源:

    api_call("people/21", :put, {:person => { :first => "Bob" } })

使用 DELETE 删除资源:

    api_call("calls/41", :delete)

关闭 api_key 的自动插入:

    api_call("calls/41", :get, {}, {:api_key => false})

使用错误的 api_key:

    api_call("calls/41", :get, {}, {:api_key => "wrong"})

作为 json 使用(默认为 xml):

    api_call("calls/41", :get, {}, {:format => "json"})

关于ruby-on-rails - 测试 Rails REST XML API 的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/752636/

相关文章:

ruby-on-rails - Rails Devise-omniauth 路线指向 passthru 而不是 twitter

ruby-on-rails - 如何从 swagger 发送 header 参数

javascript - 持续从 XML 节点获取文本

php 脚本无法读取带有冒号的 xml 数据 (:)

java - 脚轮性能问题

ruby-on-rails - Rails Time Select,重新排列组件

ruby-on-rails - Ruby on rails - Authlogic : periodically check if user session is valid

ios - XCode 11.4 - 在 UITest 中重新安装应用程序失败 : "Could not locate installed application"

javascript - CasperJS 和警告框

ruby-on-rails - 如何测试复合 Rails 模型范围?