RSpec将POST参数转换为字符串?(测试文件上传器)

dMi*_*Mix 6 rspec ruby-on-rails 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", 
          :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
Run Code Online (Sandbox Code Playgroud)

在rspec测试中,它是POST给控制器:

post :create, :legal_register_id => "1", :register => {"file" => mock_file}
Run Code Online (Sandbox Code Playgroud)

但它在实际控制器中打破了这一行:

CSV.parse(params[:register][:file].read.force_encoding('UTF-8'))
Run Code Online (Sandbox Code Playgroud)

因为params [:register] [:file]被解释为字符串而不是actiondispatch对象:

undefined method `read' for "#<ActionDispatch::Http::UploadedFile:0x00000108de3da8>":String
Run Code Online (Sandbox Code Playgroud)

这是rspec的标准行为吗?有没有办法通过参数传递对象?

She*_*aun 2

将参数对象转换为字符串的不是 RSpec,而是 Rails 3.1。

您可以通过使用此答案fixture_file_upload中的描述来解决它。