diff --git a/app/controllers/similar_topics_controller.rb b/app/controllers/similar_topics_controller.rb index 31bfe272605..1f0a84d84f8 100644 --- a/app/controllers/similar_topics_controller.rb +++ b/app/controllers/similar_topics_controller.rb @@ -19,10 +19,11 @@ class SimilarTopicsController < ApplicationController params.require(:title) params.require(:raw) title, raw = params[:title], params[:raw] - [:title, :raw].each { |key| check_length_of(key, params[key]) } + invalid_length = [:title, :raw].any? { |key| check_invalid_length(key, params[key]) } - # Only suggest similar topics if the site has a minimum amount of topics present. - return render json: [] unless Topic.count_exceeds_minimum? + # Only suggest similar topics if the site has a minimum amount of topics present + # and params are long enough. + return render json: [] if invalid_length || !Topic.count_exceeds_minimum? topics = Topic.similar_to(title, raw, current_user).to_a topics.map! {|t| SimilarTopic.new(t) } @@ -31,9 +32,9 @@ class SimilarTopicsController < ApplicationController protected - def check_length_of(key, attr) + def check_invalid_length(key, attr) str = (key == :raw) ? "body" : key.to_s - raise Discourse::InvalidParameters.new(key) if attr.length < SiteSetting.send("min_#{str}_similar_length") + attr.length < SiteSetting.send("min_#{str}_similar_length") end end diff --git a/spec/controllers/similar_topics_controller_spec.rb b/spec/controllers/similar_topics_controller_spec.rb index 5d5bc09ff43..fc6c3f9d47f 100644 --- a/spec/controllers/similar_topics_controller_spec.rb +++ b/spec/controllers/similar_topics_controller_spec.rb @@ -14,14 +14,20 @@ describe SimilarTopicsController do expect { xhr :get, :index, title: title }.to raise_error(ActionController::ParameterMissing) end - it "raises an error if the title length is below the minimum" do + it "returns no results if the title length is below the minimum" do + Topic.expects(:similar_to).never SiteSetting.stubs(:min_title_similar_length).returns(100) - expect { xhr :get, :index, title: title, raw: raw }.to raise_error(Discourse::InvalidParameters) + xhr :get, :index, title: title, raw: raw + json = ::JSON.parse(response.body) + expect(json["similar_topics"].size).to eq(0) end - it "raises an error if the body length is below the minimum" do + it "returns no results if the body length is below the minimum" do + Topic.expects(:similar_to).never SiteSetting.stubs(:min_body_similar_length).returns(100) - expect { xhr :get, :index, title: title, raw: raw }.to raise_error(Discourse::InvalidParameters) + xhr :get, :index, title: title, raw: raw + json = ::JSON.parse(response.body) + expect(json["similar_topics"].size).to eq(0) end describe "minimum_topics_similar" do