class RuboCop::Cop::RSpec::ImplicitSubject
it { expect(named_subject).to be_truthy }
# good
end
is_expected.to be_truthy
it do
# good
end
expect(subject).to be_truthy
it do
# bad
it { is_expected.to be_truthy }
# good
it { expect(subject).to be_truthy }
# bad
@example ‘EnforcedStyle: require_implicit`
it { expect(subject).to be_truthy }
# good
it { is_expected.to be_truthy }
# bad
@example `EnforcedStyle: disallow`
end
is_expected.to be_truthy
it do
end
expect(subject).to be_truthy
foo = 1
it do
# good
end
is_expected.to be_truthy
foo = 1
it do
# bad
@example `EnforcedStyle: single_statement_only`
end
expect(subject).to be_truthy
it do
it { is_expected.to be_truthy }
# good
end
is_expected.to be_truthy
it do
# bad
@example `EnforcedStyle: single_line_only` (default)
This cop can be configured using the `EnforcedStyle` option
Checks for usage of implicit subject (`is_expected` / `should`).
def autocorrect(corrector, node)
def autocorrect(corrector, node) case node.method_name when :expect corrector.replace(node, 'is_expected') when :is_expected corrector.replace(node.location.selector, 'expect(subject)') when :should corrector.replace(node.location.selector, 'expect(subject).to') when :should_not corrector.replace(node.location.selector, 'expect(subject).not_to') end end
def example_of(node)
def example_of(node) node.each_ancestor.find do |ancestor| example?(ancestor) end end
def implicit_subject_in_non_its?(node)
def implicit_subject_in_non_its?(node) implicit_subject?(node) && !its?(node) end
def implicit_subject_in_non_its_and_non_single_line?(node)
def implicit_subject_in_non_its_and_non_single_line?(node) implicit_subject_in_non_its?(node) && !single_line?(node) end
def implicit_subject_in_non_its_and_non_single_statement?(node)
def implicit_subject_in_non_its_and_non_single_statement?(node) implicit_subject_in_non_its?(node) && !single_statement?(node) end
def invalid?(node)
def invalid?(node) case style when :require_implicit explicit_unnamed_subject?(node) when :disallow implicit_subject_in_non_its?(node) when :single_line_only implicit_subject_in_non_its_and_non_single_line?(node) when :single_statement_only implicit_subject_in_non_its_and_non_single_statement?(node) end end
def its?(node)
def its?(node) example_of(node)&.method?(:its) end
def message(_node)
def message(_node) case style when :require_implicit MSG_REQUIRE_IMPLICIT else MSG_REQUIRE_EXPLICIT end end
def on_send(node)
def on_send(node) return unless invalid?(node) add_offense(node) do |corrector| autocorrect(corrector, node) end end
def single_line?(node)
def single_line?(node) example_of(node)&.single_line? end
def single_statement?(node)
def single_statement?(node) !example_of(node)&.body&.begin_type? end