Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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])

My code 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

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 #

like image 941
user1466717 Avatar asked Aug 25 '12 11:08

user1466717


People also ask

What is a file test?

The operand used by the file tests can be either a file handle or a file name. The file tests work by internally calling the operating system to determine information about the file in question. The operators will evaluate to true if the test succeeds and false if it does not.


1 Answers

You need to include 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
like image 181
Henrik N Avatar answered Oct 02 '22 14:10

Henrik N