From 12bed81187dd5b041a735af8e9cb5a5f96b4b75a Mon Sep 17 00:00:00 2001 From: Matt Jankowski Date: Fri, 5 Jan 2024 10:13:59 -0500 Subject: [PATCH] Add validation specs to `CustomFilter` model (#28600) --- app/models/custom_filter.rb | 6 +++++- spec/models/custom_filter_spec.rb | 35 +++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 spec/models/custom_filter_spec.rb diff --git a/app/models/custom_filter.rb b/app/models/custom_filter.rb index 9c936fed39..0ee9e35328 100644 --- a/app/models/custom_filter.rb +++ b/app/models/custom_filter.rb @@ -143,6 +143,10 @@ class CustomFilter < ApplicationRecord end def context_must_be_valid - errors.add(:context, I18n.t('filters.errors.invalid_context')) if context.empty? || context.any? { |c| !VALID_CONTEXTS.include?(c) } + errors.add(:context, I18n.t('filters.errors.invalid_context')) if invalid_context_value? + end + + def invalid_context_value? + context.blank? || context.difference(VALID_CONTEXTS).any? end end diff --git a/spec/models/custom_filter_spec.rb b/spec/models/custom_filter_spec.rb new file mode 100644 index 0000000000..9404936337 --- /dev/null +++ b/spec/models/custom_filter_spec.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe CustomFilter do + describe 'Validations' do + it 'requires presence of title' do + record = described_class.new(title: '') + record.valid? + + expect(record).to model_have_error_on_field(:title) + end + + it 'requires presence of context' do + record = described_class.new(context: nil) + record.valid? + + expect(record).to model_have_error_on_field(:context) + end + + it 'requires non-empty of context' do + record = described_class.new(context: []) + record.valid? + + expect(record).to model_have_error_on_field(:context) + end + + it 'requires valid context value' do + record = described_class.new(context: ['invalid']) + record.valid? + + expect(record).to model_have_error_on_field(:context) + end + end +end