假设我有一个通过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'变量缺少post数据:
{"department_id"=>234, "controller"=>"employees", "action"=>"create"}
我检查了'xml_out'的内容,它确实包含正确格式的XML。我做错了什么?
谢谢你的帮助
尝试将代码更改为:
post :create, :department_id => 234, :employees => Hash.from_xml(xml_out)
编辑
从注释来看,最终的解决方案是:
post :create, :department_id => 234, :employees => Hash.from_xml(xml_out)["employees"]