FIX: Abort CensoredWordsValidator early if censored_words_regexp nil (#8375)
* Abort CensoredWordsValidator early if censored_words_regexp nil. Sometimes censored_words_regex can end up nil, erroring the validator. This handles the nil condition and also adds a spec for the validator
This commit is contained in:
parent
7543db086a
commit
d45bd7f131
|
@ -2,9 +2,13 @@
|
|||
|
||||
class CensoredWordsValidator < ActiveModel::EachValidator
|
||||
def 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)
|
||||
)
|
||||
end
|
||||
|
|
|
@ -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
|
Loading…
Reference in New Issue