Ruby:HTTParty:无法正确格式化XML POST数据?

时间:2011-07-07 13:47:29

标签: ruby-on-rails ruby xml http-post httparty

注意:“对象”是一个占位符工作,因为我认为我不应该说控制器具体做什么。

所以,我有多种方法可以调用我的应用程序API,以下是在命令行中使用的方法:

curl -H 'Content-Type: application/xml' -d '<object><name>Test API object</name><password>password</password><description>This is a test object</description></object>' "http://acme.example.dev/objects.xml?api_key=1234"

以上命令在devlog中生成以下请求:

Processing ObjectsController#create to xml (for 127.0.0.1 at 2011-07-07 09:17:51) [POST]
  Parameters: {"format"=>"xml", "action"=>"create", "api_key"=>"1234", "controller"=>"objects", 
  "object"=>{"name"=>"Test API object", "description"=>"This is a test object", "password"=>"[FILTERED]"}}

现在,我正在尝试使用API​​为操作编写测试,以确保API工作,以及控制器。 这是我当前(损坏的)httparty命令:

  response = post("create", :api_key => SharedTest.user_api_key, :xml => data, :format => "xml")

此命令在testlog中生成以下请求:

Processing ObjectsController#create to xml (for 0.0.0.0 at 2011-07-07 09:37:35) [POST]
  Parameters: {
        "xml"=>"<object><name><![CDATA[first post]]></name>
                    <description><![CDATA[Things are not as they used to be]]></description>
                    <password><![CDATA[WHEE]]></password>
                </object>", 
                "format"=>"xml", 
                "api_key"=>"the_hatter_wants_to_have_tea1", 
                "action"=>"create", 
                "controller"=>"objects

因此,正如您所看到的,命令行命令实际上是从xml生成对象哈希,而httparty命令最终保留在xml中,这会导致create方法出现问题,因为它需要哈希。

任何想法/适当的文件? 目前的文档说,帖子需要一个网址和“选项”,然后从不说明可用的选项


*的 *修改
根据@ Casper的建议,我的方法现在看起来像这样:

def post_through_api_to_url(url, data, api_key = SharedTest.user_api_key)

  response = post("create", {
    :query => {
      :api_key => api_key
    },
    :headers => {
      "Content-Type" => "application/xml"
    },
    :body => data
  })
  ap @request.env["REQUEST_URI"]
  assert_response :success

  return response
end

不幸的是,assert_response失败了,因为通过api密钥的身份验证失败了。 看看request_uri的情况,api_key没有正确设置......它显示:

api_key%5D=the_hatter_wants_to_have_tea1"

但它应该是等于,没有%5D(右方括号)

2 个答案:

答案 0 :(得分:1)

我认为你应该如何使用它:

options = {
  :query => {
    :api_key => 1234
  },

  :headers => {
    "Content-Type" => "application/xml"
  },

  :body => "<xmlcode>goes here</xmlcode>"
}

post("/create", options)

答案 1 :(得分:0)

原谅我对它的基本要求,但如果你只想发送一个变量作为参数,为什么不按照Casper的建议去做,只是这样做:

post("/create?api_key=1234", options)

或者不是测试HTTParty访问API的特性,也许使用Rack::Test编写测试?非常粗略的例子......

require "rack/test"
require "nokogiri"

class ObjectsTest < Test::Unit::TestCase
  include Rack::Test::Methods

  def app
    MyApp.new
  end

  def create_an_object(o)
    authorize "x", "1234" # or however you want to authenticate using query params
    header 'Accept', 'text/xml'
    header 'Content-Type', 'text/xml'
    body o.to_xml
    post "/create"

    xml = Nokogiri::XML(last_response.body)
    assert something_logic_about(xml)
  end

end