복붙노트

[RUBY-ON-RAILS] RSpec에를 사용하여 파일 업로드를 테스트 - 레일

RUBY-ON-RAILS

RSpec에를 사용하여 파일 업로드를 테스트 - 레일

나는 레일에서 파일 업로드를 테스트 할 수 있지만,이 작업을 수행하는 방법을 모르겠습니다.

다음은 제어 코드는 다음과 같습니다

def uploadLicense
    #Create the license object
    @license = License.create(params[:license]) 


    #Get Session ID
    sessid = session[:session_id]

    puts "\n\nSession_id:\n#{sessid}\n"

    #Generate a random string
    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
    newpass = ""
    1.upto(5) { |i| newpass << chars[rand(chars.size-1)] }

    #Get the original file name
    upload=params[:upload]
    name =  upload['datafile'].original_filename 

    @license.format = File.extname(name)

    #calculate license ID and location
    @license.location = './public/licenses/' + sessid + newpass + name 

    #Save the license file
    #Fileupload.save(params[:upload], @license.location) 
    File.open(@license.location, "wb") { |f| f.write(upload['datafile'].read) }

     #Set license ID
    @license.license_id = sessid + newpass

    #Save the license
    @license.save

    redirect_to :action => 'show', :id => @license.id 
end

나는이 사양을 시도하지만, 작품을 나던 :

it "can upload a license and download a license" do
    file = File.new(Rails.root + 'app/controllers/lic.xml')
    license = HashWithIndifferentAccess.new
    license[:datafile] = file
    info = {:id => 4}
    post :uploadLicense, {:license => info, :upload => license}
end

어떻게 RSpec에를 사용하여 파일 업로드를 시뮬레이션 할 수 있습니다?

해결법

  1. ==============================

    1.당신은 테스트 파일 업로드에 fixture_file_upload 방법을 사용할 수 있습니다 : "{Rails.root} / 스펙 / 설비 / 파일"디렉토리에 테스트 파일을 넣어

    당신은 테스트 파일 업로드에 fixture_file_upload 방법을 사용할 수 있습니다 : "{Rails.root} / 스펙 / 설비 / 파일"디렉토리에 테스트 파일을 넣어

    before :each do
      @file = fixture_file_upload('files/test_lic.xml', 'text/xml')
    end
    
    it "can upload a license" do
      post :uploadLicense, :upload => @file
      response.should be_success
    end
    

    혹시 PARAMS [ '업로드'] [ '데이터 파일']의 형태로 파일을 기대하고 있었다

    it "can upload a license" do
      file = Hash.new
      file['datafile'] = @file
      post :uploadLicense, :upload => file
      response.should be_success
    end
    
  2. ==============================

    2.나는 당신이 혼자 RSpec을을 사용하여 파일 업로드를 테스트 할 수있는 경우 아닙니다. 당신은 카피 바라를 시도?

    나는 당신이 혼자 RSpec을을 사용하여 파일 업로드를 테스트 할 수있는 경우 아닙니다. 당신은 카피 바라를 시도?

    그것은 요구 사양에서 카피 바라의 attach_file 방법을 사용하여 테스트 파일 업로드에 쉽습니다.

    예를 들어 (이 코드는 데모입니다) :

    it "can upload a license" do
      visit upload_license_path
      attach_file "uploadLicense", /path/to/file/to/upload
      click_button "Upload License"
    end
    
    it "can download an uploaded license" do
      visit license_path
      click_link "Download Uploaded License"
      page.should have_content("Uploaded License")
    end
    
  3. ==============================

    3.당신이 랙 :: 테스트 *를 포함 할 경우, 단순히 시험 방법을 포함한다

    당신이 랙 :: 테스트 *를 포함 할 경우, 단순히 시험 방법을 포함한다

    describe "my test set" do
      include Rack::Test::Methods
    

    다음은 UploadedFile 방법을 사용할 수 있습니다 :

    post "/upload/", "file" => Rack::Test::UploadedFile.new("path/to/file.ext", "mime/type")
    

    * 참고 : 내 예는 랙 확장시나에 기초하고, 또한 사용 랙 레일로 작동해야 TTBOMK

  4. ==============================

    4.나는 RSpec에를 사용하여이 작업을 완료하지 않은,하지만 난 사진을 업로드 유사한 무언가를 테스트 : 단위 테스트를해야합니까. 내가 ActionDispatch의 인스턴스로 업로드 된 파일을 설정 : HTTP를 : UploadedFile는 등 다음 :

    나는 RSpec에를 사용하여이 작업을 완료하지 않은,하지만 난 사진을 업로드 유사한 무언가를 테스트 : 단위 테스트를해야합니까. 내가 ActionDispatch의 인스턴스로 업로드 된 파일을 설정 : HTTP를 : UploadedFile는 등 다음 :

    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
    

    또한 당신을 위해 뭔가 비슷한 힘 작동합니다.

  5. ==============================

    5.나는이 모두가 작업을 얻을 포함 추가했다 :

    나는이 모두가 작업을 얻을 포함 추가했다 :

    describe "my test set" do
      include Rack::Test::Methods
      include ActionDispatch::TestProcess
    
  6. ==============================

    6.나는 레일 6, RSpec에 함께했고, 랙 :: 테스트를하는 방법이다 :: UploadedFile

    나는 레일 6, RSpec에 함께했고, 랙 :: 테스트를하는 방법이다 :: UploadedFile

    describe 'POST /create' do
      it 'responds with success' do
        post :create, params: {
          license: {
            picture: Rack::Test::UploadedFile.new("#{Rails.root}/spec/fixtures/test-pic.png"),
            name: 'test'
          }
        }
    
        expect(response).to be_successful
      end
    end
    

    당신은 당신이 포함하는지에 대한 아니라면 DO가 NOT ActionDispatch :: TestProcess 또는 기타 코드를 포함한다.

  7. from https://stackoverflow.com/questions/7260394/test-a-file-upload-using-rspec-rails by cc-by-sa and MIT license