Class: RuboCop::Cop::Vicenzo::RSpec::NestedSubjectRedefinition

Inherits:
RSpec::Base
  • Object
show all
Defined in:
lib/rubocop/cop/vicenzo/rspec/nested_subject_redefinition.rb

Overview

Do not define the same let in nested example groups.

It makes the tests more dificult to read and indicates that exists hidden scenarios (contexts)

Examples:

Hidden context


# bad

describe '#can_access?' do
  subject(:user) { create(:user, :admin) }

  it { expect(user).to can_access(:products) }

  context 'when user is not admin' do
    subject(:user) { create(:user, :analyst) }

    it { expect(user).not_to can_access(:products) }
  end
end

# good

describe '#can_access?' do
  context 'when user is not admin' do
    subject(:user) { create(:user, :analyst) }

    it { expect(user).not_to can_access(:products) }
  end

  context 'when user is admin' do # this context was hidden
    subject(:user) { create(:user, :admin) }

    it { expect(action).to can_access(:products) }
  end
end

Constant Summary collapse

MSG =
'Subject `:%<name>s` is already defined in ancestor(s) block(s) at: %<definitions>s.'

Instance Method Summary collapse

Instance Method Details

#on_block(node) ⇒ Object Also known as: on_numblock



68
69
70
# File 'lib/rubocop/cop/vicenzo/rspec/nested_subject_redefinition.rb', line 68

def on_block(node)
  check_subject_redefinitions(node, {}) if example_group?(node)
end

#subject_name(node) {|Symbol| ... } ⇒ Object

Find a named or unnamed subject definition

Examples:

anonymous subject

subject_name(parse('subject { foo }').ast) do |name|
  name # => :subject
end

named subject

subject_name(parse('subject(:thing) { foo }').ast) do |name|
  name # => :thing
end

Parameters:

  • node (RuboCop::AST::Node)

Yields:

  • (Symbol)

    subject name



61
62
63
64
65
66
# File 'lib/rubocop/cop/vicenzo/rspec/nested_subject_redefinition.rb', line 61

def_node_matcher :subject_name, <<-PATTERN
  (block
    (send nil?
      { #Subjects.all (sym $_) | $#Subjects.all }
    ) args ...)
PATTERN