我正在向 Rails 教程示例应用添加一个 RESTful API。 Controller 操作应将 XML 作为输入并以 XML 响应。我正在尝试遵循 TDD 方法,但一直无法找到发出发布请求的确定方法。这是我的测试,是迄今为止我编写的最好的测试:
it "should increment the Relationship count" do
expect do
# valid_xml = "<xml><:followed_id>#{other_user.id}</:followed_id></xml>"
valid_xml = { followed_id: other_user.id }.to_xml
post :create, relationship: valid_xml, format: 'xml', content_type: 'application/xml'
end.to change(Relationship, :count).by(1)
end
it "should respond with success" do
# valid_xml = "<xml><:followed_id>#{other_user.id}</:followed_id></xml>"
valid_xml = { followed_id: other_user.id }.to_xml
post :create, relationship: valid_xml, format: :xml, content_type: 'application/xml'
expect(response).to be_success
end
此特定测试验证发布 XML 将创建新的关系。如您所见,我尝试了几种方法来指定输入是 XML。这是 Controller 操作:
class RelationshipsController < ApplicationController
before_action :signed_in_user
respond_to :html, :js, :xml
def create
# Problem is that the xml is not being read as such; it's a string
relationship = params[:relationship]
puts relationship
puts relationship[:followed_id]
@user = User.find(relationship[:followed_id])
current_user.follow!(@user)
respond_with @user
end
对于给定的测试, Controller 将 relationship
作为 XML 打印出来,但在下一行出现错误,它试图获取键 :followed_id
的值。对于这两个测试,错误都是 TypeError: no implicit conversion of Symbol into Integer
。
我假设这意味着 relationship
的类型是一个字符串,而不是一个散列,并且 Ruby 认为括号应该是一个索引。有谁知道我哪里出错了,无论是在测试中还是在 Controller 操作中?
有没有更好的方法来测试我应该使用的 RESTful API 或 gem?
最佳答案
XML 参数解析器已从 Rails 4.0 的核心中移除。这是由于多个漏洞以及当今大多数值得使用的 API 都是 JSON
或正在转向 JSON
的事实。
删除的功能可从 actionpack-xml_parser 获得 gem 。
关于ruby-on-rails - 如何使用 xml 作为输入测试 Rails RESTful API 发布请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25412141/