Ruby on rails RSpec将POST参数转换为字符串?(测试文件上传器)
我使用这段代码模拟文件上传的方式:Ruby on rails RSpec将POST参数转换为字符串?(测试文件上传器),ruby-on-rails,rspec,rspec-rails,Ruby On Rails,Rspec,Rspec Rails,我使用这段代码模拟文件上传的方式: 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",
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 :create, :legal_register_id => "1", :register => {"file" => mock_file}
CSV.parse(params[:register][:file].read.force_encoding('UTF-8'))
但它在实际控制人中打破了这条线:
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
“#”的未定义方法“read”:字符串
这是rspec的标准行为吗?有没有办法通过参数传递对象?您可能需要使用以下命令:ActionController::TestUploadedFile 而不是实际的ActionDispatch文件 有关使用示例,请参见其他S/O问题: 尽管这一条建议你可以利用你所拥有的:
也认为它可能是RSPEC不处理的一个问题:登记= = {file:=BLA}:登记号={“文件”=> BLA}}/P>< P>这不是RSPEC将您的PARAM对象转换为字符串,它是Rails 3.1。p>
您可以使用中所述的
fixture\u file\u upload
绕过它。。。。你让它工作了吗?我的回答有用吗?