我想在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模拟文件上传?
答案 0 :(得分:283)
您可以使用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
答案 1 :(得分:53)
我不确定您是否可以单独使用RSpec测试文件上传。你试过Capybara吗?
从请求规范中使用capybara的attach_file
方法测试文件上传很容易。
例如(此代码仅为演示):
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
答案 2 :(得分:32)
如果包含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")
*注意:我的示例基于Sinatra,它扩展了Rack,但应该使用Rails,它也使用Rack,TTBOMK
答案 3 :(得分:16)
我没有使用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
类似的东西也可能对你有用。
答案 4 :(得分:5)
我必须添加这两个包含以使其正常工作:
describe "my test set" do
include Rack::Test::Methods
include ActionDispatch::TestProcess
答案 5 :(得分:0)
这就是我使用Rails 6
,RSpec
和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::TestProcess
或任何其他代码,除非您确定要包含的内容。