RSpec 将 POST 参数转换为字符串? (测试文件上传器)
我使用这段代码来模仿文件上传的方式:
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 的标准行为吗?有没有办法通过参数传递对象?
I am using this block of code to mimic the way files are uploaded:
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
In the rspec test it is POST'd to the controller:
post :create, :legal_register_id => "1", :register => {"file" => mock_file}
But it breaks this line in the actual controller:
CSV.parse(params[:register][:file].read.force_encoding('UTF-8'))
Because params[:register][:file] is being interpretted as a string instead of an actiondispatch object:
undefined method `read' for "#<ActionDispatch::Http::UploadedFile:0x00000108de3da8>":String
Is this standard behavior for rspec? Is there a way to pass objects via params?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将参数对象转换为字符串的不是 RSpec,而是 Rails 3.1。
您可以按照此答案中所述使用
fixture_file_upload
来解决这个问题。It's not RSpec that's converting your param objects to strings, it's Rails 3.1.
You can get around it by using
fixture_file_upload
as described in this answer.您可能需要使用这个:ActionController::TestUploadedFile
而不是实际的 ActionDispatch 文件
有关使用示例,请参阅其他 S/O 问题:
如何在 Rails 中测试文件上传?
尽管此建议您可以使用您所拥有的:
使用 rspec -rails 测试文件上传
还请考虑它可能是某种东西rspec 不处理 :register => 的狡猾{:file =>blah} 与 :register => 相同{'文件' =>废话}
You might need to use this: ActionController::TestUploadedFile
instead of an actual ActionDispatch file
See this other S/O question for an example of use:
How do I test a file upload in rails?
Though this one suggests you can use what you've got:
test a file upload using rspec - rails
Also consider it might be something dodgy with rspec not treating :register => {:file =>blah} the same as :register => {'file' => blah}