From bb25e4b29d583cbceb503d79abed5629b4ca589e Mon Sep 17 00:00:00 2001 From: Marc-Andre Lafortune Date: Tue, 23 Jun 2020 15:56:57 -0400 Subject: [PATCH] Fix Metrics/PerceivedComplexity for case with else --- lib/rubocop/cop/metrics/perceived_complexity.rb | 5 +++-- .../cop/metrics/perceived_complexity_spec.rb | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/rubocop/cop/metrics/perceived_complexity.rb b/lib/rubocop/cop/metrics/perceived_complexity.rb index 93bb75ea5ff..41cb33c601c 100644 --- a/lib/rubocop/cop/metrics/perceived_complexity.rb +++ b/lib/rubocop/cop/metrics/perceived_complexity.rb @@ -42,12 +42,13 @@ def complexity_score_for(node) # If cond is nil, that means each when has an expression that # evaluates to true or false. It's just an alternative to # if/elsif/elsif... so the when nodes count. + nb_branches = node.when_branches.length + (node.else_branch ? 1 : 0) if node.condition.nil? - node.when_branches.length + nb_branches else # Otherwise, the case node gets 0.8 complexity points and each # when gets 0.2. - (0.8 + 0.2 * node.when_branches.length).round + (0.8 + 0.2 * nb_branches).round end when :if node.else? && !node.elsif? ? 2 : 1 diff --git a/spec/rubocop/cop/metrics/perceived_complexity_spec.rb b/spec/rubocop/cop/metrics/perceived_complexity_spec.rb index 8eb470188a5..e53f09c1f92 100644 --- a/spec/rubocop/cop/metrics/perceived_complexity_spec.rb +++ b/spec/rubocop/cop/metrics/perceived_complexity_spec.rb @@ -156,6 +156,22 @@ def method_name RUBY end + it 'counts else in a case with no argument' do + expect_offense(<<~RUBY) + def method_name + ^^^^^^^^^^^^^^^ Perceived complexity for method_name is too high. [4/1] + case + when value == 1 + call_foo + when value == 2 + call_bar + else + call_baz + end + end + RUBY + end + it 'registers an offense for &&' do expect_offense(<<~RUBY) def method_name