Skip to content

Commit e6eef78

Browse files
authored
Merge pull request #200 from BigG1947/fix-errrors-with-invalid-csv
Fix errors with invalid csv
2 parents 9ca311a + 4e83191 commit e6eef78

File tree

4 files changed

+36
-0
lines changed

4 files changed

+36
-0
lines changed

lib/active_admin_import/dsl.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ def active_admin_import(options = {}, &block)
9494
end
9595
rescue ActiveRecord::Import::MissingColumnError,
9696
NoMethodError,
97+
ArgumentError,
9798
ActiveRecord::StatementInvalid,
9899
CSV::MalformedCSVError,
99100
ActiveAdminImport::Exception => e

lib/active_admin_import/model.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,8 @@ def file_path
103103

104104
def encode_file
105105
data = File.read(file_path)
106+
return if data.empty?
107+
106108
File.open(file_path, 'w') do |f|
107109
f.write(encode(data))
108110
end
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Birthday,Name,Last name
2+
1986-05-01,John,Doe
3+
1988-11-16,Jane,Roe, exceeded value

spec/import_spec.rb

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,36 @@ def upload_file!(name, ext = 'csv')
424424
expect(Author.count).to eq(2)
425425
end
426426
end
427+
428+
context 'with empty csv and auto detect encoding' do
429+
let(:options) do
430+
attributes = { force_encoding: :auto }
431+
{ template_object: ActiveAdminImport::Model.new(attributes) }
432+
end
433+
434+
before do
435+
upload_file!(:empty)
436+
end
437+
438+
it 'should render warning' do
439+
expect(page).to have_content I18n.t('active_admin_import.file_empty_error')
440+
expect(Author.count).to eq(0)
441+
end
442+
end
443+
444+
context 'with csv which has exceeded values' do
445+
before do
446+
upload_file!(:authors_values_exceeded_headers)
447+
end
448+
449+
it 'should render warning' do
450+
# 5 columns: 'birthday, name, last_name, created_at, updated_at'
451+
# 6 values: '"1988-11-16", "Jane", "Roe", " exceeded value", datetime, datetime'
452+
msg = 'Number of values (6) exceeds number of columns (5)'
453+
expect(page).to have_content I18n.t('active_admin_import.file_error', message: msg)
454+
expect(Author.count).to eq(0)
455+
end
456+
end
427457
end
428458

429459
context 'with callback procs options' do

0 commit comments

Comments
 (0)