使用 XML 主体进行 Rails API 功能测试
我已经使用 shoulda 测试框架为 Rails 中构建的 API 端点编写了功能测试。
示例如下所示:
setup do
authenticated_xml_request('xml-file-name')
post :new
end
should respond_with :success
authenticated_xml_request 是一个测试帮助器方法,用于设置 @request.env['RAW_POST_DATA'] 包含 XML 内容。
将应用从 rails 2.3.3 升级到 rails 2.3.8 后,功能测试失败,因为收到的 XML 内容未合并到 params 哈希中。
我通过 @request.accept = 设置正确的 mime 类型的请求 “text/xml”
我可以使用 request.raw_post 检查请求的内容,但我想保持当前设置正常工作。
此外,在开发模式下使用 cURL 或任何其他库 (rest_http) 从终端运行测试,API 运行得非常好。
非常感谢任何提示或帮助。
I've written functional tests for API endpoints built in Rails using shoulda testing framework.
An example looks like the following:
setup do
authenticated_xml_request('xml-file-name')
post :new
end
should respond_with :success
authenticated_xml_request is a test helper method that sets
@request.env['RAW_POST_DATA'] with XML content.
After upgrading the app from rails 2.3.3 to rails 2.3.8, the functional tests are failing because the XML content received is not merged in the params hash.
I'm setting the request with the correct mime type via @request.accept =
"text/xml"
I'm able to inspect the content of the request using request.raw_post but i'd like to keep the current setup working.
Also, running a test from the terminal using cURL or any other library (rest_http) in development mode, the API works perfectly well.
Any tips or help is much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
现在更简单了:
请注意,您必须指定适当的“CONTENT_TYPE”。在其他情况下,您的请求将作为“application/x-www-form-urlencoded”,并且 xml 将无法正确解析。
Now it's simpler:
Note that you have to specify appropriate "CONTENT_TYPE". In other case your request will go as 'application/x-www-form-urlencoded' and xml won't be parsed properly.
我通过向 Rails 添加自定义补丁(test_process.rb 文件)来将传入的 xml 转换为哈希值,然后合并到参数哈希值中,从而解决了该问题。
第 439 行:
parameters ||= {}
parameters.merge!(Hash.from_xml(@request.env['RAW_POST_DATA'])) if @request.env['RAW_POST_DATA'] && @request.env['CONTENT_TYPE']=='application/xml'
I solved the issue by adding a custom patch to rails (test_process.rb file) to convert incoming xml to hash then merge into parameters hash.
on line 439:
parameters ||= {}
parameters.merge!(Hash.from_xml(@request.env['RAW_POST_DATA'])) if @request.env['RAW_POST_DATA'] && @request.env['CONTENT_TYPE']=='application/xml'