简体   繁体   English

如何测试文件上传模型?

[英]How to test a model for file upload?

I have a model where I use the method to upload images 我有一个模型,我使用该方法上传图像

In Image controller I call DataFile.save_image_file(params[:upload]) 在Image控制器中,我调用DataFile.save_image_file(params [:upload])

My code data_file.rb 我的代码data_file.rb

      def self.save_image_file(upload)
        file_name = upload['datafile'].original_filename  if  (upload['datafile'] !='')    
        file = upload['datafile'].read    

        file_type = file_name.split('.').last
        new_name_file = Time.now.to_i
        name_folder = new_name_file
        new_file_name_with_type = "#{new_name_file}." + file_type
        new_file_name_thumb_with_type = "#{new_name_file}-thumb." + file_type

        image_root = "#{RAILS_CAR_IMAGES}"


          Dir.mkdir(image_root + "#{name_folder}");
          File.open(image_root + "#{name_folder}/" + new_file_name_with_type, "wb")  do |f|  
            f.write(file)
          end

[new_name_file, new_file_name_with_type, new_file_name_thumb_with_type]

      end

I want to test it in RSpec 我想在RSpec中测试它

data_file_spec.rb data_file_spec.rb

require 'spec_helper'

describe DataFile do
  describe "Should save image file" do 


    before(:each) do
      @file = fixture_file_upload('/files/test-bus-1.jpg', 'image/jpg')
    end

    it "Creating new car name and thumb name" do
      @get_array = save_file(@file)
      @get_array[:new_name_file].should_not be_nil
    end

  end
end

But test doesn't work 但测试不起作用

Failure/Error: @file = fixture_file_upload('/files/test-bus-1.jpg', 'image/jpg') NoMethodError: undefined method `fixture_file_upload' for # 失败/错误:@file = fixture_file_upload('/ files / test-bus-1.jpg','image / jpg')NoMethodError:未定义的方法`fixture_file_upload'for#

You need to include ActionDispatch::TestProcess . 您需要包含ActionDispatch::TestProcess Try something like: 尝试类似的东西:

require 'spec_helper'

describe DataFile do
  describe "Should save image file" do 
    let(:file) do
      extend ActionDispatch::TestProcess
      fixture_file_upload('/files/test-bus-1.jpg', 'image/jpg')
    end

    it "Creating new car name and thumb name" do
      @get_array = save_file(file)
      @get_array[:new_name_file].should_not be_nil
    end
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM