Skip to content

Commit c689419

Browse files
committed
Fix bugs with caching and format validation when importing files
1 parent 160a796 commit c689419

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

lib/active_admin_import/model.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ module CONST
3737
validate :file_contents_present, if: ->(me) { me.file.present? }
3838

3939
before_validation :unzip_file, if: ->(me) { me.archive? && me.allow_archive? }
40-
before_validation :encode_file, if: ->(me) { me.force_encoding? && me.file.present? }
40+
after_validation :encode_file, if: ->(me) { me.force_encoding? && me.file.present? }
4141

4242
attr_reader :attributes
4343

@@ -48,6 +48,7 @@ def initialize(args = {})
4848
end
4949

5050
def assign_attributes(args = {}, new_record = false)
51+
args[:file] = nil unless args.key?(:file)
5152
@attributes.merge!(args)
5253
@new_record = new_record
5354
args.keys.each do |key|
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Name,Last name,Birthday
2+
John,Doe,1986-05-01

spec/import_spec.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -588,4 +588,42 @@ def upload_file!(name, ext = 'csv')
588588
expect { add_author_resource(options) }.to raise_error(ArgumentError)
589589
end
590590
end
591+
592+
context 'when submitting empty form after validation error' do
593+
let(:options) { {} }
594+
595+
before do
596+
add_author_resource(options)
597+
visit '/admin/authors/import'
598+
end
599+
600+
it 'should NOT reuse cached file from previous submission' do
601+
expect do
602+
upload_file!(:author_broken_header)
603+
expect(page).to have_content("can't write unknown attribute")
604+
end.not_to change { Author.count }
605+
606+
# Second submission without selecting a file
607+
expect do
608+
find_button('Import').click
609+
expect(page).to have_content(I18n.t('active_admin_import.no_file_error'))
610+
end.not_to change { Author.count }
611+
end
612+
end
613+
614+
context 'when importing file with invalid format and auto force_encoding' do
615+
let(:options) { { template_object: ActiveAdminImport::Model.new(force_encoding: :auto) } }
616+
617+
before do
618+
add_author_resource(options)
619+
visit '/admin/authors/import'
620+
end
621+
622+
it 'should reject invalid file format before encoding' do
623+
expect do
624+
upload_file!(:author_invalid_format, 'txt')
625+
expect(page).to have_content I18n.t('active_admin_import.file_format_error')
626+
end.not_to change { Author.count }
627+
end
628+
end
591629
end

0 commit comments

Comments
 (0)