gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:26:25 26 4
gpt4 key购买 nike

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

这是 Controller 代码:

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

关于ruby-on-rails - 使用 rspec 测试文件上传 - Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7260394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com