使用 rspec - rails 测试文件上传 [英] test a file upload using rspec - rails
本文介绍了使用 rspec - rails 测试文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 rails 中测试文件上传,但不知道如何执行此操作.
I want to test a file upload in rails, but am not sure how to do this.
这是控制器代码:
def uploadLicense
#Create the license object
@license = License.create(params[:license])
#Get Session ID
sessid = session[:session_id]
puts "
Session_id:
#{sessid}
"
#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
如何使用 rspec 模拟文件上传?
How can I simulate the file upload, using rspec?
推荐答案
您可以使用 fixture_file_upload 方法进行测试文件上传:将您的测试文件放在 "{Rails.root}/spec/fixtures/files" 目录
You can use fixture_file_upload method to test file uploading: Put your test file in "{Rails.root}/spec/fixtures/files" directory
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 - rails 测试文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文