test a file upload using rspec - rails

Solution 1:

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

In case you were expecting the file in the form of params['upload']['datafile']

it "can upload a license" do
  file = Hash.new
  file['datafile'] = @file
  post :uploadLicense, :upload => file
  response.should be_success
end

Solution 2:

I am not sure if you can test file uploads using RSpec alone. Have you tried Capybara?

It's easy to test file uploads using capybara's attach_file method from a request spec.

For example (this code is a demo only):

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