From 35fd625c064629183681244988128e0d66bf6b36 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Fri, 1 Jul 2016 14:36:30 +0100 Subject: [PATCH] Fix ActiveRecord::RecordNotUnique errors When someone does a double submit we can get uniqueness exceptions from the database. In these circumstances just redirect to the thank you page as the first request will have sent the email. --- app/controllers/signatures_controller.rb | 2 ++ spec/controllers/signatures_controller_spec.rb | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/app/controllers/signatures_controller.rb b/app/controllers/signatures_controller.rb index 07ec448e4..2b382eca8 100644 --- a/app/controllers/signatures_controller.rb +++ b/app/controllers/signatures_controller.rb @@ -149,6 +149,8 @@ def handle_new_signature(petition) format.html { render :new } end end + rescue ActiveRecord::RecordNotUnique => e + redirect_to thank_you_petition_signatures_url(petition) end def validate_sponsor diff --git a/spec/controllers/signatures_controller_spec.rb b/spec/controllers/signatures_controller_spec.rb index c1450915c..ba38f7665 100644 --- a/spec/controllers/signatures_controller_spec.rb +++ b/spec/controllers/signatures_controller_spec.rb @@ -430,6 +430,19 @@ def do_post(options = {}) expect(response).to render_template(:new) end end + + context "when a race condition occurs" do + let(:exception) { ActiveRecord::RecordNotUnique.new("PG::UniqueViolation") } + before do + FactoryGirl.create(:validated_signature, signature_params.merge(petition_id: petition.id)) + allow_any_instance_of(Signature).to receive(:save).and_raise(exception) + end + + it "redirects to the thank you page" do + do_post(stage: 'done') + expect(response).to redirect_to("https://petition.parliament.uk/petitions/#{petition.id}/signatures/thank-you") + end + end end context "when the petition is closed" do