diff --git a/app/models/top_topic.rb b/app/models/top_topic.rb index 6b0c7c9050b..93da90bf32b 100644 --- a/app/models/top_topic.rb +++ b/app/models/top_topic.rb @@ -45,11 +45,12 @@ class TopTopic < ActiveRecord::Base end def self.validate_period(period) - if period.blank? || !periods.include?(period.to_sym) - raise Discourse::InvalidParameters.new( - "Invalid period. Valid periods are #{periods.join(", ")}", - ) - end + @invalid_period_error ||= + Discourse::InvalidParameters.new("Invalid period. Valid periods are #{periods.join(", ")}") + + raise @invalid_period_error if period.blank? || !periods.include?(period.to_sym) + rescue NoMethodError + raise @invalid_period_error end private diff --git a/spec/models/top_topic_spec.rb b/spec/models/top_topic_spec.rb index 0906b9a7db8..33d59206ffc 100644 --- a/spec/models/top_topic_spec.rb +++ b/spec/models/top_topic_spec.rb @@ -34,6 +34,36 @@ RSpec.describe TopTopic do end end + describe ".validate_period" do + context "when passing a valid period" do + it do + expect { described_class.validate_period(described_class.periods.first) }.not_to raise_error + end + end + + context "when passing a blank value" do + it do + expect { described_class.validate_period(nil) }.to raise_error(Discourse::InvalidParameters) + end + end + + context "when passing an invalid period" do + it do + expect { described_class.validate_period("bi-weekly") }.to raise_error( + Discourse::InvalidParameters, + ) + end + end + + context "when passing a non-string value" do + it do + expect { described_class.validate_period(ActionController::Parameters) }.to raise_error( + Discourse::InvalidParameters, + ) + end + end + end + describe "#compute_top_score_for" do fab!(:user) fab!(:coding_horror)