2011-10-31 6 views
6

Sto usando questo blocco di codice per imitare il modo in cui i file vengono caricati:RSpec che converte i parametri POST in stringa? (File uploader test)

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 

Nel test RSpec è POST'd al controller:

post :create, :legal_register_id => "1", :register => {"file" => mock_file} 

Ma rompe questa riga nel controller attuale:

CSV.parse(params[:register][:file].read.force_encoding('UTF-8')) 

poiché params [: register] [: File] è in corso interpretato nel modo una stringa invece di un oggetto actiondispatch:

undefined method `read' for "#<ActionDispatch::Http::UploadedFile:0x00000108de3da8>":String 

Questo comportamento standard per rspec? C'è un modo per passare oggetti tramite parametri?

+0

quindi ... hai funzionato? La mia risposta è stata d'aiuto? –

risposta

2

Non è RSpec che converte gli oggetti param in stringhe, è Rails 3.1.

È possibile aggirare il problema utilizzando fixture_file_upload come descritto in this answer.

0

Potrebbe essere necessario utilizzare questo: ActionController :: TestUploadedFile invece di un file effettivo ActionDispatch

Vedi quest'altra domanda S/O per un esempio di utilizzo: How do I test a file upload in rails?

Anche se questo si suggerisce può uso quello che hai: test a file upload using rspec - rails

considera anche che potrebbe essere qualcosa di poco raccomandabile con RSpec non trattare: register => {: file => blah} ° Lo stesso di: register => {'file' => blah}