A platform for community discussion. Free, open, simple.
FIX: Abort CensoredWordsValidator early if censored_words_regexp nil (#8375)
Martin Brennand45bd7f1318c
diff --git a/lib/validators/censored_words_validator.rb b/lib/validators/censored_words_validator.rbindex d36a0931d8c..b65f6620e34 100644--- a/lib/validators/censored_words_validator.rb+++ b/lib/validators/censored_words_validator.rb@@ -2,9 +2,13 @@class CensoredWordsValidator < ActiveModel::EachValidatordef validate_each(record, attribute, value)- if WordWatcher.words_for_action(:censor).present? && (censored_words = censor_words(value, censored_words_regexp)).present?+ words_regexp = censored_words_regexp+ if WordWatcher.words_for_action(:censor).present? && !words_regexp.nil?+ censored_words = censor_words(value, words_regexp)+ return if censored_words.blank?record.errors.add(- attribute, :contains_censored_words,+ attribute,+ :contains_censored_words,censored_words: join_censored_words(censored_words))enddiff --git a/spec/lib/validators/censored_words_validator_spec.rb b/spec/lib/validators/censored_words_validator_spec.rbnew file mode 100644index 00000000000..391c9143631--- /dev/null+++ b/spec/lib/validators/censored_words_validator_spec.rb@@ -0,0 +1,50 @@+# frozen_string_literal: true++require 'rails_helper'++describe CensoredWordsValidator do+ let(:value) { 'some new bad text' }+ let(:record) { Fabricate(:post, raw: 'this is a test') }+ let(:attribute) { :raw }++ describe "#validate_each" do+ context "when there are censored words for action" do+ let!(:watched_word) { Fabricate(:watched_word, action: WatchedWord.actions[:censor], word: 'bad') }++ context "when there is a nil word_matcher_regexp" do+ before do+ WordWatcher.stubs(:word_matcher_regexp).returns(nil)+ end++ it "adds no errors to the record" do+ validate+ expect(record.errors.empty?).to eq(true)+ end+ end++ context "when there is word_matcher_regexp" do+ context "when the new value does not contain the watched word" do+ let(:value) { 'some new good text' }++ it "adds no errors to the record" do+ validate+ expect(record.errors.empty?).to eq(true)+ end+ end++ context "when the new value does contain the watched word" do+ let(:value) { 'some new bad text' }++ it "adds errors to the record" do+ validate+ expect(record.errors.empty?).to eq(false)+ end+ end+ end+ end+ end++ def validate+ described_class.new(attributes: :test).validate_each(record, attribute, value)+ end+end