我正在使用这段代码来模仿文件上传的方式:
def mock_file
file = File.new((Rails.root + "public/checklist_items_template.csv"),"r")
image = ActionDispatch::Http::UploadedFile.new(
:filename => "checklist_items_template.csv",
:type => "text/csv",
:head => "Content-Disposition: form-data;
name=\"checklist_items_template.csv\";
filename=\"checklist_items_template.csv\"
Content-Type: text/csv\r\n",
:tempfile => file)
return image
end
在 rspec 测试中,它被 POST 到控制器:
post :create, :legal_register_id => "1", :register => {"file" => mock_file}
但它在实际控制器中打破了这一行:
CSV.parse(params[:register][:file].read.force_encoding('UTF-8'))
因为 params[:register][:file] 被解释为字符串而不是 actiondispatch 对象:
undefined method `read' for "#<ActionDispatch::Http::UploadedFile:0x00000108de3da8>":String
这是 rspec 的标准行为吗?有没有办法通过参数传递对象?