简体   繁体   English

如何测试文件上传和控制器?

[英]How can I test the file upload and controller?

My view 我的观点

  <%= form_tag({:action => 'upload_image', :car_id => @car.id}, :multipart => true) do %>
    <label for="upload_file"><%= t('field.select_image') %></label>
    <%= file_field 'upload', 'datafile' %>&nbsp;<%= submit_tag t('field.upload_file') %>
  <% end %>

My controller 我的控制器

  def upload_image   
    if params[:upload].present? && params[:car_id].present?
      DataFile.save_image_file(params[:upload][:datafile], params[:car_id]) # My methods to save image and other operations with file

    end
    redirect_to images_path(:car_id => params[:car_id])
  end

My Rspec Test (doesn't work) 我的Rspec测试(无效)

before :each do
  @car = FactoryGirl.create(:car)
  @file = fixture_file_upload('/files/test-bus-1.jpg', 'image/jpg')

end

it "can upload a car" do
  post :upload_image, :upload => @file, :car_id => @car.id
  response.should redirect_to images_path(:car_id => @car.id)
end

Error: Failure/Error: post :upload_image, :upload => @file, :car_id => @car.id NoMethodError: undefined method `[]' for # File:/tmp/test-bus-1.jpg20120826-29027-plg28d 错误:失败/错误:发布:upload_image,:upload => @file,:car_id => @ car.id NoMethodError:#File:/tmp/test-bus-1.jpg20120826-29027-的未定义方法'[]' plg28d

What's wrong? 怎么了?

在我看来,根据您如何设置表单(因为您正在调用params[:upload][:datafile] ),您需要将rspec测试更改为:

post :upload_image, :upload => { :datafile => @file }, :car_id => @car.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM