IT

rspec-rails를 사용하여 파일 업로드 테스트

lottoking 2020. 6. 22. 07:31
반응형

rspec-rails를 사용하여 파일 업로드 테스트


레일에서 파일 업로드를 테스트하고 싶지만 어떻게해야하는지 잘 모르겠습니다.

컨트롤러 코드는 다음과 같습니다.

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을 사용하여 파일 업로드를 어떻게 시뮬레이트 할 수 있습니까?


fixture_file_upload 메소드를 사용 하여 파일 업로드를 테스트 할 수 있습니다 . 테스트 파일을 "{Rails.root} / spec / fixtures / files" 디렉토리에 두십시오.

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 [ 'upload'] [ 'datafile'] 형식의 파일을 예상 한 경우

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

RSpec 만 사용하여 파일 업로드를 테스트 할 수 있는지 잘 모르겠습니다. 당신은 시도 카피 바라를 ?

attach_file요청 사양에서 capybara의 방법을 사용하여 파일 업로드를 쉽게 테스트 할 수 있습니다.

예를 들어 (이 코드는 데모 전용) :

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

if you include Rack::Test*, simply include the test methods

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

then you can use the UploadedFile method:

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

*NOTE: My example is based on Sinatra, which extends Rack, but should work with Rails, which also uses Rack, TTBOMK


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.


I had to add both of these includes to get it working:

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

참고URL : https://stackoverflow.com/questions/7260394/test-a-file-upload-using-rspec-rails

반응형