Sha256: f2b44102bcb69b5b60cac202647cb825d31839f71a6af94486e15ac6fe9f1d29

Contents?: true

Size: 1.61 KB

Versions: 13

Compression:

Stored size: 1.61 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module RSpec
      # Checks for opportunities to use `expect { ... }.to output`.
      #
      # @example
      #   # bad
      #   $stdout = StringIO.new
      #   my_app.print_report
      #   $stdout = STDOUT
      #   expect($stdout.string).to eq('Hello World')
      #
      #   # good
      #   expect { my_app.print_report }.to output('Hello World').to_stdout
      class ExpectOutput < Cop
        MSG = 'Use `expect { ... }.to output(...).to_%<name>s` '\
              'instead of mutating $%<name>s.'.freeze

        def_node_matcher :hook?, Hooks::ALL.block_pattern

        def on_gvasgn(node)
          return unless inside_example_scope?(node)

          variable_name, _rhs = *node
          name = variable_name[1..-1]
          return unless name.eql?('stdout') || name.eql?('stderr')

          add_offense(node, location: :name, message: format(MSG, name: name))
        end

        private

        # Detect if we are inside the scope of a single example
        #
        # We want to encourage using `expect { ... }.to output` so
        # we only care about situations where you would replace with
        # an expectation. Therefore, assignments to stderr or stdout
        # within a `before(:all)` or otherwise outside of an example
        # don't matter.
        def inside_example_scope?(node)
          return false if node.nil? || example_group?(node)
          return true if example?(node)
          return RuboCop::RSpec::Hook.new(node).example? if hook?(node)

          inside_example_scope?(node.parent)
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
rubocop-rspec-1.27.0 lib/rubocop/cop/rspec/expect_output.rb
rubocop-rspec-1.26.0 lib/rubocop/cop/rspec/expect_output.rb
rubocop-rspec-1.25.1 lib/rubocop/cop/rspec/expect_output.rb
rubocop-rspec-1.25.0 lib/rubocop/cop/rspec/expect_output.rb
rubocop-rspec-1.24.0 lib/rubocop/cop/rspec/expect_output.rb
rubocop-rspec-1.23.0 lib/rubocop/cop/rspec/expect_output.rb
rubocop-rspec-1.22.2 lib/rubocop/cop/rspec/expect_output.rb
rubocop-rspec-1.22.1 lib/rubocop/cop/rspec/expect_output.rb
rubocop-rspec-1.22.0 lib/rubocop/cop/rspec/expect_output.rb
rubocop-rspec-1.21.0 lib/rubocop/cop/rspec/expect_output.rb
rubocop-rspec-1.20.1 lib/rubocop/cop/rspec/expect_output.rb
rubocop-rspec-1.20.0 lib/rubocop/cop/rspec/expect_output.rb
rubocop-rspec-1.19.0 lib/rubocop/cop/rspec/expect_output.rb