Handle unique voucher code exception

Rails validation doesn't handle unique validation for soft deleted
object. So we rescue the exception raise by the database and display
a nice error message. We don't want an enterprise to be able to reuse
a code in case the voucher get reactivated.
This commit is contained in:
Gaetan Craig-Riou
2023-09-07 15:13:47 +02:00
parent 63cd8ccf28
commit f225cd78df
2 changed files with 19 additions and 0 deletions

View File

@@ -22,6 +22,11 @@ module Admin
rescue ActiveRecord::SubclassNotFound
@voucher.errors.add(:type)
render_error
rescue ActiveRecord::RecordNotUnique
# Rails unique validation doesn't work with soft deleted object, so we rescue the database
# exception to display a nice message to the user
@voucher.errors.add(:code, :taken)
render_error
end
private

View File

@@ -81,6 +81,20 @@ describe "/admin/enterprises/:enterprise_id/vouchers", type: :request do
end
end
context "with a code used by a deactivated voucher" do
before do
voucher = create(:voucher, code:, enterprise:)
voucher.destroy
end
it "render the new page with a code taken error" do
create_voucher
expect(response).to render_template("admin/vouchers/new")
expect(flash[:error]).to eq("Code has already been taken")
end
end
it "redirects to admin enterprise setting page, voucher panel" do
create_voucher