假设我有一个通过POST处理XML的REST服务:
class DepartmentsController < ApplicationController
# POST /departments/1/employees.xml
def create
params[:employees].each do |e| # <employees type="array">
@employee = Employee.new(e)
@employee.save
end
respond_to do |format|
format.any { head status }
end
end
end
它期望的XML类似于:
<?xml version="1.0" encoding="UTF-8"?>
<exmployees type="array">
<employee>
...
</employe>
<employee>
...
</employe>
</employees>
该服务在与iPhone应用程序交互时按预期工作,但我无法使用我的功能测试(我是Rails新手)。
所以这就是我正在尝试的事情:
test "should create employees with client data" do
xml_out = ""
xml = Builder::XmlMarkup.new(:target => xml_out, :indent => 2)
xml.instruct!
xml.employees :type => "array" do
xml.employee do
# ...
end
end
assert_difference('Employee.count') do
@request.env['RAW_POST_BODY'] = xml_out
post :create, :department_id => 234
end
end
我得到的错误:
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
似乎'params'变量缺少帖子数据:
{"department_id"=>234, "controller"=>"employees", "action"=>"create"}
我已经检查了'xml_out'的内容,它确实包含了正确形成的XML。我做错了什么?
感谢您的帮助:)
答案 0 :(得分:3)
尝试将代码更改为:
post :create, :department_id => 234, :employees => Hash.from_xml(xml_out)
修改强>
从评论中,最终的解决方案是:
post :create, :department_id => 234, :employees => Hash.from_xml(xml_out)["employees"]