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 ?
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