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

Inherits:
Cop
  • Object
show all
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.'

Constants inherited from Cop

Cop::DEFAULT_CONFIGURATION, Cop::DEFAULT_PATTERN_RE

Constants included from RSpec::Language

RSpec::Language::ALL, RSpec::Language::RSPEC

Instance Method Summary collapse

Methods inherited from Cop

inherited, #relevant_file?

Instance Method Details

#autocorrect(node) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
# File 'lib/rubocop/cop/rspec/shared_context.rb', line 79

def autocorrect(node)
  lambda do |corrector|
    context_with_only_examples(node.parent) do
      corrector.replace(node.loc.selector, 'shared_examples')
    end

    examples_with_only_context(node.parent) do
      corrector.replace(node.loc.selector, 'shared_context')
    end
  end
end

#on_block(node) ⇒ Object



69
70
71
72
73
74
75
76
77
# File 'lib/rubocop/cop/rspec/shared_context.rb', line 69

def on_block(node)
  context_with_only_examples(node) do
    add_shared_item_offense(node.send_node, MSG_EXAMPLES)
  end

  examples_with_only_context(node) do
    add_shared_item_offense(node.send_node, MSG_CONTEXT)
  end
end