From c6894199a864a08b87fbf190ddf8a3bde9a881df Mon Sep 17 00:00:00 2001 From: Denys Metelov Date: Tue, 20 Jan 2026 22:47:55 +0100 Subject: [PATCH] Fix bugs with caching and format validation when importing files --- lib/active_admin_import/model.rb | 3 +- spec/fixtures/files/author_invalid_format.txt | 2 + spec/import_spec.rb | 38 +++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 spec/fixtures/files/author_invalid_format.txt diff --git a/lib/active_admin_import/model.rb b/lib/active_admin_import/model.rb index f3fde01..716f794 100644 --- a/lib/active_admin_import/model.rb +++ b/lib/active_admin_import/model.rb @@ -37,7 +37,7 @@ module CONST validate :file_contents_present, if: ->(me) { me.file.present? } before_validation :unzip_file, if: ->(me) { me.archive? && me.allow_archive? } - before_validation :encode_file, if: ->(me) { me.force_encoding? && me.file.present? } + after_validation :encode_file, if: ->(me) { me.force_encoding? && me.file.present? } attr_reader :attributes @@ -48,6 +48,7 @@ def initialize(args = {}) end def assign_attributes(args = {}, new_record = false) + args[:file] = nil unless args.key?(:file) @attributes.merge!(args) @new_record = new_record args.keys.each do |key| diff --git a/spec/fixtures/files/author_invalid_format.txt b/spec/fixtures/files/author_invalid_format.txt new file mode 100644 index 0000000..cd4fcd6 --- /dev/null +++ b/spec/fixtures/files/author_invalid_format.txt @@ -0,0 +1,2 @@ +Name,Last name,Birthday +John,Doe,1986-05-01 diff --git a/spec/import_spec.rb b/spec/import_spec.rb index cc4db50..5128da2 100644 --- a/spec/import_spec.rb +++ b/spec/import_spec.rb @@ -588,4 +588,42 @@ def upload_file!(name, ext = 'csv') expect { add_author_resource(options) }.to raise_error(ArgumentError) end end + + context 'when submitting empty form after validation error' do + let(:options) { {} } + + before do + add_author_resource(options) + visit '/admin/authors/import' + end + + it 'should NOT reuse cached file from previous submission' do + expect do + upload_file!(:author_broken_header) + expect(page).to have_content("can't write unknown attribute") + end.not_to change { Author.count } + + # Second submission without selecting a file + expect do + find_button('Import').click + expect(page).to have_content(I18n.t('active_admin_import.no_file_error')) + end.not_to change { Author.count } + end + end + + context 'when importing file with invalid format and auto force_encoding' do + let(:options) { { template_object: ActiveAdminImport::Model.new(force_encoding: :auto) } } + + before do + add_author_resource(options) + visit '/admin/authors/import' + end + + it 'should reject invalid file format before encoding' do + expect do + upload_file!(:author_invalid_format, 'txt') + expect(page).to have_content I18n.t('active_admin_import.file_format_error') + end.not_to change { Author.count } + end + end end