test a file upload using rspec - rails

后端 未结 6 2110
梦毁少年i
梦毁少年i 2020-11-27 09:52

I want to test a file upload in rails, but am not sure how to do this.

Here is the controller code:

def uploadLicense
    #Create the license object
         


        
6条回答
  •  孤街浪徒
    2020-11-27 10:38

    I haven't done this using RSpec, but I do have a Test::Unit test that does something similar for uploading a photo. I set up the uploaded file as an instance of ActionDispatch::Http::UploadedFile, as follows:

    test "should create photo" do
      setup_file_upload
      assert_difference('Photo.count') do
        post :create, :photo => @photo.attributes
      end
      assert_redirected_to photo_path(assigns(:photo))
    end
    
    
    def setup_file_upload
      test_photo = ActionDispatch::Http::UploadedFile.new({
        :filename => 'test_photo_1.jpg',
        :type => 'image/jpeg',
        :tempfile => File.new("#{Rails.root}/test/fixtures/files/test_photo_1.jpg")
      })
      @photo = Photo.new(
        :title => 'Uploaded photo', 
        :description => 'Uploaded photo description', 
        :filename => test_photo, 
        :public => true)
    end
    

    Something similar might work for you also.

提交回复
热议问题