使用真正的 XML 和 JSON 请求/响应自动测试 Rails 应用程序,作为 API 文档?

oma*_*oma 5 xml integration-testing json ruby-on-rails

我应该善待我的 Web 服务消费者并为他们提供一些很好的示例,即使维护大型 xml 请求测试并不有趣。有没有更好的方法来成为一个好的 WS 提供者?

我没有html。该应用程序同时接受 XML 和 JSON,因此为了确保 API 示例(xml 和 json)的有效性,我想在集成套件中证明它们是正确的。

在你的回答中,我想看一些例子,而不是仅仅“尝试黄瓜/webrat/capybara”。没有html很难找到howto。感谢您的帮助!

oma*_*oma 1

我有这个独立的脚本,使我能够发送 xml 请求,但需要服务器:

require 'rubygems'
require 'net/http'
require 'json'
url = URI.parse('http://localhost:3030/myresource.xml')
request = Net::HTTP::Post.new(url.path)
request.content_type="text/xml"
request.basic_auth('user', 'secret')
request.body = "<?xml version='1.0' encoding='UTF-8'?><somedata><name>Test Name 1</name><description>Some data for testing</description></somedata>"
response = Net::HTTP.start(url.host, url.port) {|http| http.request(request)}
puts response
Run Code Online (Sandbox Code Playgroud)

最后,我能够使用 rspec 2 在不启动服务器的情况下完成此操作。将其放入下面的规范文件中,spec/requests使我能够在没有 webrat 或 capybara 的情况下在我的应用程序中执行此操作。

对于 XML

post("/myresource.xml", 
     some_xml_string,
     {"CONTENT_TYPE" => "text/xml",
      "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials("user", "secret")})
Run Code Online (Sandbox Code Playgroud)

和 JSON

post("/myresource.json",
      some_json_string,
      {"CONTENT_TYPE" => "application/json",
       "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials("user", "secret")})
Run Code Online (Sandbox Code Playgroud)

some_xml_string现在我想我可以从远程资源构建,例如我的文档 xml 或 json 文件(某些 http:// 资源)。是的,它需要更多的维护,并且测试会很脆弱。我将不得不更多地考虑这一点...更改外部人员使用的 API 并不是一件可以掉以轻心的事情,总是需要进行很多权衡。欢迎更好的建议!