Class: RuboCop::Cop::RSpec::NamedSubject
- Defined in:
- lib/rubocop/cop/rspec/named_subject.rb
Overview
Checks for explicitly referenced test subjects.
RSpec lets you declare an “implicit subject” using ‘subject { … }` which allows for tests like `it { is_expected.to be_valid }`. If you need to reference your test subject you should explicitly name it using `subject(:your_subject_name) { … }`. Your test subjects should be the most important object in your tests so they deserve a descriptive name.
This cop can be configured in your configuration using the ‘IgnoreSharedExamples` which will not report offenses for implicit subjects in shared example groups.
Constant Summary collapse
- MSG =
'Name your test subject if you need to reference it explicitly.'
Instance Method Summary collapse
- #example_or_hook_block?(node) ⇒ Object
- #ignored_shared_example?(node) ⇒ Boolean
- #on_block(node) ⇒ Object
- #shared_example?(node) ⇒ Object
- #subject_usage(node) ⇒ Object
Methods inherited from Base
inherited, #on_new_investigation
Methods included from RSpec::Language::NodePattern
Methods included from RSpec::Language
#example?, #example_group?, #example_group_with_body?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?
Instance Method Details
#example_or_hook_block?(node) ⇒ Object
48 49 |
# File 'lib/rubocop/cop/rspec/named_subject.rb', line 48 def_node_matcher :example_or_hook_block?, block_pattern('{#Examples.all #Hooks.all}') |
#ignored_shared_example?(node) ⇒ Boolean
68 69 70 71 |
# File 'lib/rubocop/cop/rspec/named_subject.rb', line 68 def ignored_shared_example?(node) cop_config['IgnoreSharedExamples'] && node.each_ancestor(:block).any?(&method(:shared_example?)) end |
#on_block(node) ⇒ Object
58 59 60 61 62 63 64 65 66 |
# File 'lib/rubocop/cop/rspec/named_subject.rb', line 58 def on_block(node) if !example_or_hook_block?(node) || ignored_shared_example?(node) return end subject_usage(node) do |subject_node| add_offense(subject_node.loc.selector) end end |
#shared_example?(node) ⇒ Object
52 53 |
# File 'lib/rubocop/cop/rspec/named_subject.rb', line 52 def_node_matcher :shared_example?, block_pattern('#SharedGroups.examples') |
#subject_usage(node) ⇒ Object
56 |
# File 'lib/rubocop/cop/rspec/named_subject.rb', line 56 def_node_search :subject_usage, '$(send nil? :subject)' |