class RuboCop::Cop::RSpec::ImplicitSubject
Checks for usage of implicit subject (`is_expected` / `should`).
This cop can be configured using the `EnforcedStyle` option
@example `EnforcedStyle: single_line_only` (default)
# bad it do is_expected.to be_truthy end # good it { is_expected.to be_truthy } it do expect(subject).to be_truthy end
@example `EnforcedStyle: single_statement_only`
# bad it do foo = 1 is_expected.to be_truthy end # good it do foo = 1 expect(subject).to be_truthy end it do is_expected.to be_truthy end
@example `EnforcedStyle: disallow`
# bad it { is_expected.to be_truthy } # good it { expect(subject).to be_truthy }
Constants
- MSG
- RESTRICT_ON_SEND
Public Instance Methods
on_send(node)
click to toggle source
# File lib/rubocop/cop/rspec/implicit_subject.rb, line 57 def on_send(node) return unless implicit_subject?(node) return if valid_usage?(node) add_offense(node) do |corrector| autocorrect(corrector, node) end end
Private Instance Methods
allowed_by_style?(example)
click to toggle source
# File lib/rubocop/cop/rspec/implicit_subject.rb, line 87 def allowed_by_style?(example) case style when :single_line_only example.single_line? when :single_statement_only !example.body.begin_type? else false end end
autocorrect(corrector, node)
click to toggle source
# File lib/rubocop/cop/rspec/implicit_subject.rb, line 68 def autocorrect(corrector, node) replacement = 'expect(subject)' case node.method_name when :should replacement += '.to' when :should_not replacement += '.not_to' end corrector.replace(node.loc.selector, replacement) end
valid_usage?(node)
click to toggle source
# File lib/rubocop/cop/rspec/implicit_subject.rb, line 80 def valid_usage?(node) example = node.ancestors.find { |parent| example?(parent) } return false if example.nil? example.method?(:its) || allowed_by_style?(example) end