Ruby-on-rails 使用 rspec - rails 测试文件上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7260394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:53:15  来源:igfitidea点击:

test a file upload using rspec - rails

ruby-on-railsfile-uploadtddrspec-rails

提问by user727403

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

我想在 rails 中测试文件上传,但不知道如何执行此操作。

Here is the controller code:

这是控制器代码:

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

I have tried this spec, but it doesnt work:

我已经尝试过这个规范,但它不起作用:

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

How can I simulate the file upload, using rspec?

如何使用 rspec 模拟文件上传?

回答by ebsbk

You can use fixture_file_uploadmethod to test file uploading: Put your test file in "{Rails.root}/spec/fixtures/files"directory

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

In case you were expecting the file in the form of params['upload']['datafile']

如果您希望文件以params['upload']['datafile'] 的形式出现

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

回答by Ken

I am not sure if you can test file uploads using RSpec alone. Have you tried Capybara?

我不确定您是否可以单独使用 RSpec 测试文件上传。你试过水豚吗?

It's easy to test file uploads using capybara's attach_filemethod from a request spec.

使用attach_file请求规范中的capybara方法测试文件上传很容易。

For example (this code is a demo only):

例如(此代码仅为演示):

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

回答by zedd45

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

如果包含 Rack::Test*,只需包含测试方法

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

then you can use the UploadedFile method:

那么你可以使用 UploadedFile 方法:

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

*注意:我的示例基于 Sinatra,它扩展了 Rack,但应该与 Rails 一起使用,Rails 也使用 Rack、TTBOMK

回答by Dave Isaacs

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:

我没有使用 RSpec 完成此操作,但我确实有一个 Test::Unit 测试,它对上传照片执行类似的操作。我将上传的文件设置为 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

Something similar might work for you also.

类似的东西也可能对你有用。

回答by nfriend21

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

我必须添加这两个包括才能使其正常工作:

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

回答by thisismydesign

This is how I did it with Rails 6, RSpecand Rack::Test::UploadedFile

我就是这样做的Rails 6RSpec并且Rack::Test::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 include ActionDispatch::TestProcessor any other code unless you're sure about what you're including.

ActionDispatch::TestProcess除非您确定要包含的内容,否则请勿包含或任何其他代码。