Class: RuboCop::Cop::RSpec::SharedContext

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rspec/shared_context.rb

Overview

Checks for proper shared_context and shared_examples usage.

If there are no examples defined, use shared_context. If there is no setup defined, use shared_examples.

Examples:

# bad
RSpec.shared_context 'only examples here' do
  it 'does x' do
  end

  it 'does y' do
  end
end

# good
RSpec.shared_examples 'only examples here' do
  it 'does x' do
  end

  it 'does y' do
  end
end
# bad
RSpec.shared_examples 'only setup here' do
  subject(:foo) { :bar }

  let(:baz) { :bazz }

  before do
    something
  end
end

# good
RSpec.shared_context 'only setup here' do
  subject(:foo) { :bar }

  let(:baz) { :bazz }

  before do
    something
  end
end

Constant Summary collapse

MSG_EXAMPLES =
"Use `shared_examples` when you don't define context."
MSG_CONTEXT =
"Use `shared_context` when you don't define examples."

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_pattern, #send_pattern

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?

Instance Method Details

#context?(node) ⇒ Object


64
65
66
67
68
69
70
71
72
73
# File 'lib/rubocop/cop/rspec/shared_context.rb', line 64

def_node_search :context?, <<-PATTERN
  (
    send #rspec? {
      #Subjects.all
      #Helpers.all
      #Includes.context
      #Hooks.all
    } ...
  )
PATTERN

#examples?(node) ⇒ Object


60
61
# File 'lib/rubocop/cop/rspec/shared_context.rb', line 60

def_node_search :examples?,
send_pattern('{#Includes.examples #Examples.all}')

#on_block(node) ⇒ Object


82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/rubocop/cop/rspec/shared_context.rb', line 82

def on_block(node)
  context_with_only_examples(node) do
    add_offense(node.send_node, message: MSG_EXAMPLES) do |corrector|
      corrector.replace(node.send_node.loc.selector, 'shared_examples')
    end
  end

  examples_with_only_context(node) do
    add_offense(node.send_node, message: MSG_CONTEXT) do |corrector|
      corrector.replace(node.send_node.loc.selector, 'shared_context')
    end
  end
end

#shared_context(node) ⇒ Object


76
77
# File 'lib/rubocop/cop/rspec/shared_context.rb', line 76

def_node_matcher :shared_context,
block_pattern('#SharedGroups.context')

#shared_example(node) ⇒ Object


79
80
# File 'lib/rubocop/cop/rspec/shared_context.rb', line 79

def_node_matcher :shared_example,
block_pattern('#SharedGroups.examples')