8

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?

kush
  • 16,408
  • 17
  • 48
  • 65

2 Answers2

2

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.

Community
  • 1
  • 1
Shevaun
  • 1,208
  • 12
  • 19
0

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}

Community
  • 1
  • 1
Taryn East
  • 27,486
  • 9
  • 86
  • 108