From 3432c96ede8d541c53af223800f2b6dd6f750f56 Mon Sep 17 00:00:00 2001 From: Molly Struve Date: Fri, 15 May 2020 15:18:28 -0500 Subject: [PATCH] [deploy] Limit Response Template Count for Users (#7890) --- app/models/response_template.rb | 10 ++++++++++ spec/models/response_template_spec.rb | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/app/models/response_template.rb b/app/models/response_template.rb index 4be8a38cb..f4663a468 100644 --- a/app/models/response_template.rb +++ b/app/models/response_template.rb @@ -24,10 +24,20 @@ class ResponseTemplate < ApplicationRecord inclusion: { in: EMAIL_CONTENT_TYPES, message: EMAIL_VALIDATION_MSG }, if: -> { type_of&.include?("email") } validate :user_nil_only_for_user_nil_types + validate :template_count + + private def user_nil_only_for_user_nil_types return unless user_id.present? && USER_NIL_TYPE_OF_TYPES.include?(type_of) errors.add(:type_of, USER_NIL_TYPE_OF_MSG) end + + def template_count + return unless user + return if user.trusted || user.response_templates.count <= 30 + + errors.add(:user, "Response template limit of 30 per user has been reached") + end end diff --git a/spec/models/response_template_spec.rb b/spec/models/response_template_spec.rb index 660634354..f8ddedf24 100644 --- a/spec/models/response_template_spec.rb +++ b/spec/models/response_template_spec.rb @@ -27,4 +27,22 @@ RSpec.describe ResponseTemplate, type: :model do end end end + + describe "user validation" do + it "validates the number of templates for a normal user" do + user = create(:user) + create_list(:response_template, 30, user_id: user.id) + invalid_template = create(:response_template, user_id: user.id) + + expect(invalid_template).not_to be_valid + expect(invalid_template.errors.full_messages.join).to include("limit of 30 per user has been reached") + end + + it "allows trusted users to have unlimited templates" do + user = create(:user, :trusted) + create_list(:response_template, 31, user_id: user.id) + + expect(user.response_templates.all?(&:valid?)).to be(true) + end + end end