1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
# frozen_string_literal: true
module RuboCop
module Cop
module RSpec
# 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.
#
# @example
# # 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
#
# @example
# # 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
#
class SharedContext < Base
extend AutoCorrector
MSG_EXAMPLES = "Use `shared_examples` when you don't define context."
MSG_CONTEXT = "Use `shared_context` when you don't define examples."
# @!method examples?(node)
def_node_search :examples?,
send_pattern('{#Includes.examples #Examples.all}')
# @!method context?(node)
def_node_search :context?, <<-PATTERN
(
send #rspec? {
#Subjects.all
#Helpers.all
#Includes.context
#Hooks.all
} ...
)
PATTERN
# @!method shared_context(node)
def_node_matcher :shared_context,
block_pattern('#SharedGroups.context')
# @!method shared_example(node)
def_node_matcher :shared_example,
block_pattern('#SharedGroups.examples')
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
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
private
def context_with_only_examples(node)
shared_context(node) { yield if examples?(node) && !context?(node) }
end
def examples_with_only_context(node)
shared_example(node) { yield if context?(node) && !examples?(node) }
end
end
end
end
end
|