diff --git a/lib/rubocop/cop/metrics/perceived_complexity.rb b/lib/rubocop/cop/metrics/perceived_complexity.rb index 93bb75ea5ffd..41cb33c601c7 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 8eb470188a54..e53f09c1f926 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