How to Test a File Upload in Rails

How do I test a file upload in rails?

Searched for this question and could not find it, or its answer on Stack Overflow, but found it elsewhere, so I'm asking to make it available on SO.

The rails framework has a function fixture_file_upload (Rails 2 Rails 3, Rails 5), which will search your fixtures directory for the file specified and will make it available as a test file for the controller in functional testing. To use it:

1) Put your file to be uploaded in the test in your fixtures/files subdirectory for testing.

2) In your unit test you can get your testing file by calling fixture_file_upload('path','mime-type').

e.g.:

bulk_json = fixture_file_upload('files/bulk_bookmark.json','application/json')

3) call the post method to hit the controller action you want, passing the object returned by fixture_file_upload as the parameter for the upload.

e.g.:

post :bookmark, :bulkfile => bulk_json

Or in Rails 5: post :bookmark, params: {bulkfile: bulk_json}

This will run through the simulated post process using a Tempfile copy of the file in your fixtures directory and then return to your unit test so you can start examining the results of the post.

How to test that a file is uploaded in a controller?

Answer was to use fixture_file_upload: http://api.rubyonrails.org/classes/ActionDispatch/TestProcess.html#method-i-fixture_file_upload

post :update, user: { photo: fixture_file_upload('images/bob-weir.jpg', 'image/jpg') }

Also, if you wanted to use this in a factory, it would be:

Rack::Test::UploadedFile.new(File.open(File.join(Rails.root, '/spec/fixtures/images/bob-weir.jpg')))

How to test a model for file upload?

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

How do I test a file upload in rails for integration testing?

The notes here: http://apidock.com/rails/ActionController/TestProcess/fixture_file_upload indicate that you need to include a slash before the path or file name.

try fixture_file_upload('/goodsins.xls', 'text/xls') and see if that helps.

fixture_file_upload Source:

# File actionpack/lib/action_controller/test_process.rb, line 523
def fixture_file_upload(path, mime_type = nil, binary = false)
if ActionController::TestCase.respond_to?(:fixture_path)
fixture_path = ActionController::TestCase.send(:fixture_path)
end

ActionController::TestUploadedFile.new("#{fixture_path}#{path}",
mime_type, binary)
end

Update from Question Owner:

Solution:

add include ActionDispatch::TestProcess to test_helper.rb



Related Topics



Leave a reply



Submit