1

I'm trying to write spec for testing upload function and the code implementation works as expected however when I tried to write spec I'm not able to figure out why the data conversation is failing during JSON.parse. [ Rails 5.X ]

Method

def upload
  #some validation
  begin
    puts params[:file]
    json = JSON.parse(params[:file].read)
    #rest of the validation
  rescue StandardError, JSON::ParserError, HttpServices::BadHttpResponseError
      flash[:style] = :error
  end
end

Spec:

describe "upload" do
  before do
    read = file_fixture("empy_details.json").read
    @file = Hash.new
    @file['emp'] = read #debugger > @file:{emp: [{"name":"Bob","key":"201","active":true}]}
  end

  it 'should upload' do
    post :upload, params: { :file => @file }, as: :json
    expect(flash[:style]).to eq(:success)
  end
end

The method puts params[:file] prints

{"emp"=>"[{\"name\":\"Bob\",\"key\":\"201\",\"active\":true}]\n"} 

The JSON.parse fails at convert_hashes_to_parameters(key, value) method and converted gets value of "[{"name":"Bob","key":"201","active":true}]" before failing.

What am I missing ?

Tom Aranda
  • 5,919
  • 11
  • 35
  • 51
Mad-D
  • 4,479
  • 18
  • 52
  • 93
  • I am curious. What is the debugger output of `params[:file].read`? – Tom Aranda Nov 05 '17 at 22:30
  • @TomAranda: it fails during .read and if I pass with just params[:file] I still get the same error. So I'm not sure if I have to format this to Action::Dispatcher object ? if so how. – Mad-D Nov 05 '17 at 22:32
  • Don't rescue StandardError - only rescue errors that you know what to do with. It will make debugging close to impossible as it will swallow a large amount of exceptions. – max Nov 07 '17 at 00:59

1 Answers1

0

params[:file].read was throwing exception when the file was passed through Rspec and I changed the controller method code to accommodate params[:file] instead.

def upload
  #some validation
  begin
    puts params[:file]
    if params[:file].respond_to?(:read)
      json = JSON.parse(params[:file].read)
    else
      json = JSON.parse(params[:file])
    end
    #rest of the validation
  rescue StandardError, JSON::ParserError, HttpServices::BadHttpResponseError
      flash[:style] = :error
  end
end
Mad-D
  • 4,479
  • 18
  • 52
  • 93