waldyr.ar
waldyr.ar

Reputation: 15224

How to mock file to test file upload in rails 4.2.1

I'm trying to test the action to import products from a CSV.

I'm being able to get the first test to pass. The params[:file] goes to the controller as a string "#<StringIO:0x007fc0d40a0bd0>" which doesn't make my test fail but it isn't the correct behaviour.

The second test I'm getting the following error

private method `gets' called for  #<ActionDispatch::Http::UploadedFile:0x007fd391de0a00>

Here's is my spec (content is the CSV content)

  # spec/controllers/products_controller_spec.rb

  describe 'POST import with file' do
    before do
      post :import, file: file
    end

    context 'with invalid data' do
      subject { Spree::Product.count }
      let(:file) { StringIO.new("") }
      it { is_expected.to eq 0 }
    end

    context 'with valid data' do
      subject { Spree::Product.count }
      let(:file) { ActionDispatch::Http::UploadedFile.new(params) }

      let(:params) do
        {
          original_filename: 'file.csv',
          content_type: 'text/csv',
          tempfile: StringIO.new(content)
        }
      end

      it { is_expected.to eq 1 }
    end
  end

Upvotes: 2

Views: 3423

Answers (1)

Nikita Misharin
Nikita Misharin

Reputation: 2030

Try to use Rack::Test::UploadedFile to upload a test file, something like this

context 'with valid data' do
  subject { Spree::Product.count }
  let(:path_to_file) { Rails.root.join 'spec/fixtures/file.csv' }
  let(:file) { Rack::Test::UploadedFile.new path_to_file, 'text/csv' }

  it { is_expected.to eq 1 }
end

Upvotes: 7

Related Questions