【问题标题】:RSpec converting POST params to string? (testing file uploader)RSpec将POST参数转换为字符串? (测试文件上传器)
【发布时间】:2011-10-31 18:11:34
【问题描述】:

我正在使用这段代码来模拟文件的上传方式:

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 的标准行为吗?有没有办法通过参数传递对象?

【问题讨论】:

  • 所以...你让它工作了吗?我的回答有帮助吗?

标签: ruby-on-rails rspec rspec-rails


【解决方案1】:

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

您可以通过使用fixture_file_upload 来解决它,如this answer 中所述。

【讨论】:

    【解决方案2】:

    你可能需要使用这个:ActionController::TestUploadedFile 而不是实际的 ActionDispatch 文件

    有关使用示例,请参阅此其他 S/O 问题: How do I test a file upload in rails?

    虽然这个建议你可以使用你所拥有的: test a file upload using rspec - rails

    还要考虑它可能是一些狡猾的 rspec 不处理 :register => {:file =>blah} 与 :register => {'file' => blah}

    【讨论】:

      猜你喜欢
      • 2016-12-10
      • 2016-07-19
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 2015-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多