PiKaY
PiKaY

Reputation: 289

File upload testing using rspec

How do I generate a file for testing with a given size and test file upload in rspec? I want to generate the file.

I currently have the files in fixtures/files and use fixture_file_upload as a test file. I want to eliminate the need for that sample file.

Upvotes: 5

Views: 3377

Answers (2)

Muntasim
Muntasim

Reputation: 6786

If someone wants to stub uploaded file to test model logic, here is the solution:

    file = Rack::Test::UploadedFile.new(File.join(Rails.root, 'app', 'assets', 'images', 'test-file.jpg'), 'image/jpg')

    allow_any_instance_of(Model).to receive(:photo_obj).and_return file

Upvotes: -1

Kostas Rousis
Kostas Rousis

Reputation: 6068

You could use factory_girl or fabrication to mock the uploaded file.

A sample configuration for factory_girl would look like:

factory :attachment do
  supporting_documentation_file_name { 'test.pdf' }
  supporting_documentation_content_type { 'application/pdf' }
  supporting_documentation_file_size { 1024 }
end

Take a look in this nice article on why and how to do that using factory girl

This, as the article describes, requires a shift in your testing philosophy. Instead of testing the file uploading itself (which the gem you are using is already testing for you) you just focus on the necessary models.

An alternative to exercise the actual uploading can be found here Mocking file uploads in Rails 3.1 controller tests

Upvotes: 3

Related Questions