Say I have a REST service that handles an XML via POST:
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
The XML it expects is something like:
<?xml version="1.0" encoding="UTF-8"?>
<exmployees type="array">
<employee>
...
</employe>
<employee>
...
</employe>
</employees>
The service works as expected when interacting with an iPhone app, but I can’t manage to get it working with my functional test (I’m a Rails newbie).
So here’s what I’m trying:
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
And the error I’m getting:
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
It seems the ‘params’ variable is missing the post data:
{"department_id"=>234, "controller"=>"employees", "action"=>"create"}
I’ve checked the content of ‘xml_out’, and it does contain the properly formed XML. What am I doing wrong?
Thanks for your help 🙂
Try changing your code to:
EDIT
From the comments, the final solution was: