ruby-on-rails rails書 - 使用rspec-rails測試文件上傳




3 Answers

您可以使用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
controller gem

我想在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模擬文件上傳?




如果您包含Rack :: Test *,只需包含測試方法

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

那麼你可以使用UploadedFile方法:

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

*注意:我的示例基於延伸Rack的Sinatra,但應與Rails一起使用,Rails也使用Rack,TTBOMK




我不得不添加這兩個包括讓它工作:

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



Related