Enforce Uniqueness for Broadcast Titles (#8239) [deploy]

* Add uniqueness validation to broadcast titles in broadcast.rb

* WIP: properly test title uniqueness in broadcast_spec.rb

* Add unique index for title and type_of on Broadcasts
  * Adds a unique index to the Broadcasts table
  * Adds broadcast.rb to .rubocop_todo.yml

* Resolve merge conflicts

* Add spec around duplicate broadcasts in broadcasts_spec.rb

* Adjust broadcast to be inactive in broadcasts_spec.rb
This commit is contained in:
Julianna Tetreault 2020-06-02 15:43:59 -06:00 committed by GitHub
parent 40dc8d1349
commit 7af4ee034f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 21 additions and 2 deletions

View file

@ -83,6 +83,7 @@ Rails/UniqueValidationWithoutIndex:
- 'app/models/comment.rb'
- 'app/models/follow.rb'
- 'app/models/notification.rb'
- 'app/models/broadcast.rb'
# Offense count: 33
# Cop supports --auto-correct.

View file

@ -3,7 +3,8 @@ class Broadcast < ApplicationRecord
has_many :notifications, as: :notifiable, inverse_of: :notifiable
validates :title, :type_of, :processed_html, presence: true
validates :title, uniqueness: { scope: :type_of }, presence: true
validates :type_of, :processed_html, presence: true
validates :type_of, inclusion: { in: %w[Announcement Welcome] }
validate :single_active_announcement_broadcast

View file

@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_06_01_121243) do
ActiveRecord::Schema.define(version: 2020_06_02_174329) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
@ -273,6 +273,7 @@ ActiveRecord::Schema.define(version: 2020_06_01_121243) do
t.string "title"
t.string "type_of"
t.datetime "updated_at"
t.index ["title", "type_of"], name: "index_broadcasts_on_title_and_type_of", unique: true
end
create_table "buffer_updates", force: :cascade do |t|

View file

@ -5,6 +5,7 @@ RSpec.describe Broadcast, type: :model do
it { is_expected.to validate_presence_of(:type_of) }
it { is_expected.to validate_presence_of(:processed_html) }
it { is_expected.to validate_inclusion_of(:type_of).in_array(%w[Announcement Welcome]) }
it { is_expected.to validate_uniqueness_of(:title).scoped_to(:type_of) }
it { is_expected.to have_many(:notifications) }

View file

@ -112,4 +112,19 @@ RSpec.describe "/internal/broadcasts", type: :request do
end
end
end
context "with the same title and the same type_of" do
let(:super_admin) { create(:user, :super_admin) }
let(:params) { { title: "Hello!", processed_html: "<p>Hello!</p>", type_of: "Announcement" } }
before { sign_in super_admin }
it "does not allow for a second broadcast to be created" do
expect do
2.times do
post_resource
end
end.to change { Broadcast.all.count }.by(1)
end
end
end