Skip to content

Commit

Permalink
Handle non-CSV file upload errors
Browse files Browse the repository at this point in the history
  • Loading branch information
steventux committed Jul 25, 2023
1 parent 59053ce commit 3c69614
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 1 deletion.
3 changes: 3 additions & 0 deletions app/forms/support_interface/upload_form.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ def save
return false unless valid?

CreateChildrensBarredListEntries.new(file.read).call
rescue CSV::MalformedCSVError
errors.add(:file, :invalid_csv)
false
end
end
end
4 changes: 3 additions & 1 deletion app/services/create_childrens_barred_list_entries.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
require "csv"

class CreateChildrensBarredListEntries
TITLES_REGEX = /^(mr|mrs|miss|ms|dr|prof)\.? /i

def initialize(raw_data)
@raw_data = raw_data
end
Expand Down Expand Up @@ -30,7 +32,7 @@ def pad_trn(trn)
end

def format_names(names)
names.gsub!(/^(mr|mrs|miss|ms|dr|prof)\.? /i, "")
names.gsub!(TITLES_REGEX, "")
names.split(" ").map(&:capitalize).join(" ")
end
end
1 change: 1 addition & 0 deletions app/views/support_interface/uploads/new.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<%= f.govuk_error_summary %>
<%= f.govuk_file_field :file,
accept: "text/csv",
label: { text: "Select a file to upload", class: "govuk-heading-m" },
hint: { text: "You should upload your files in CSV format." } %>
Expand Down
1 change: 1 addition & 0 deletions config/locales/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ en:
attributes:
file:
blank: Please select a CSV file to upload
invalid_csv: Please ensure file is in CSV format and try again
13 changes: 13 additions & 0 deletions spec/forms/support_interface/upload_form_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,18 @@
expect { form.save }.to change { ChildrensBarredListEntry.count }.by(2)
end
end

context "when the file contents are invalid" do
let(:invalid_csv_data) { %(1, "foo", 3) }

subject(:form) do
described_class.new(file: StringIO.new(invalid_csv_data))
end

it "adds an error to the file attribute" do
expect(form.save).to eq(false)
expect(form.errors[:file]).to include("Please ensure file is in CSV format and try again")
end
end
end
end

0 comments on commit 3c69614

Please sign in to comment.