Cops
# 1,019 cops: 613 in RuboCop 1.91.0, the rest in its official plugins.
Bundler 7
- Bundler/DuplicatedGemChecks for duplicate gem entries in Gemfile.
- Bundler/DuplicatedGroupChecks for duplicate group entries in Gemfile.
- Bundler/GemCommentAdd a comment describing each gem.
- Bundler/GemFilenameEnforces the filename for managing gems.
- Bundler/GemVersionRequires or forbids specifying gem versions.
- Bundler/InsecureProtocolSourceThe source
:gemcutter,:rubygemsand:rubyforgeare deprecated because HTTP requests are insecure. Please change your source to 'https://rubygems.org' if possible, or 'http://rubygems.org' if not. - Bundler/OrderedGemsGems within groups in the Gemfile should be alphabetically sorted.
Gemspec 10
- Gemspec/AddRuntimeDependencyPrefer
add_dependencyoveradd_runtime_dependency. - Gemspec/AttributeAssignmentUse consistent style for Gemspec attributes assignment.
- Gemspec/DependencyVersionRequires or forbids specifying gem dependency versions.
- Gemspec/DeprecatedAttributeAssignmentChecks that deprecated attribute assignments are not set in a gemspec file.
- Gemspec/DevelopmentDependenciesChecks that development dependencies are specified in Gemfile rather than gemspec.
- Gemspec/DuplicatedAssignmentAn attribute assignment method calls should be listed only once in a gemspec.
- Gemspec/OrderedDependenciesDependencies in the gemspec should be alphabetically sorted.
- Gemspec/RequireMFAChecks that the gemspec has metadata to require Multi-Factor Authentication from RubyGems.
- Gemspec/RequiredRubyVersionChecks that
required_ruby_versionof gemspec is specified and equal toTargetRubyVersionof .rubocop.yml. - Gemspec/RubyVersionGlobalsUsageChecks usage of RUBY_VERSION in gemspec.
Layout 100
- Layout/AccessModifierIndentationChecks indentation of private/protected visibility modifiers.
- Layout/ArgumentAlignmentAlign the arguments of a method call if they span more than one line.
- Layout/ArrayAlignmentAlign the elements of an array literal if they span more than one line.
- Layout/AssignmentIndentationChecks the indentation of the first line of the right-hand-side of a multi-line assignment.
- Layout/BeginEndAlignmentAlign ends corresponding to begins correctly.
- Layout/BlockAlignmentAlign block ends correctly.
- Layout/BlockEndNewlinePut end statement of multiline block on its own line.
- Layout/CaseIndentationChecks how the
whenandinclauses of acaseexpression are indented. - Layout/ClassStructureEnforces a configured order of definitions within a class body.
- Layout/ClosingHeredocIndentationChecks the indentation of here document closings.
- Layout/ClosingParenthesisIndentationChecks the indentation of hanging closing parentheses.
- Layout/CommentIndentationChecks the indentation of comments.
- Layout/ConditionPositionChecks for condition placed in a confusing position relative to the keyword.
- Layout/DefEndAlignmentAlign ends corresponding to defs correctly.
- Layout/DotPositionChecks the position of the dot in multi-line method calls.
- Layout/ElseAlignmentAlign elses and elsifs correctly.
- Layout/EmptyCommentChecks empty comment.
- Layout/EmptyLineAfterGuardClauseAdd empty line after guard clause.
- Layout/EmptyLineAfterMagicCommentAdd an empty line after magic comments to separate them from code.
- Layout/EmptyLineAfterMultilineConditionEnforces empty line after multiline condition.
- Layout/EmptyLineBetweenDefsUse empty lines between class/module/method defs.
- Layout/EmptyLinesDon't use several empty lines in a row.
- Layout/EmptyLinesAfterModuleInclusionKeeps track of empty lines after module inclusion methods.
- Layout/EmptyLinesAroundAccessModifierKeep blank lines around access modifiers.
- Layout/EmptyLinesAroundArgumentsKeeps track of empty lines around method arguments.
- Layout/EmptyLinesAroundAttributeAccessorKeep blank lines around attribute accessors.
- Layout/EmptyLinesAroundBeginBodyKeeps track of empty lines around begin-end bodies.
- Layout/EmptyLinesAroundBlockBodyKeeps track of empty lines around block bodies.
- Layout/EmptyLinesAroundClassBodyKeeps track of empty lines around class bodies.
- Layout/EmptyLinesAroundExceptionHandlingKeywordsKeeps track of empty lines around exception handling keywords.
- Layout/EmptyLinesAroundMethodBodyKeeps track of empty lines around method bodies.
- Layout/EmptyLinesAroundModuleBodyKeeps track of empty lines around module bodies.
- Layout/EndAlignmentAlign ends correctly.
- Layout/EndOfLineUse Unix-style line endings.
- Layout/ExtraSpacingDo not use unnecessary spacing.
- Layout/FirstArgumentIndentationChecks the indentation of the first argument in a method call.
- Layout/FirstArrayElementIndentationChecks the indentation of the first element in an array literal.
- Layout/FirstArrayElementLineBreakChecks for a line break before the first element in a multi-line array.
- Layout/FirstHashElementIndentationChecks the indentation of the first key in a hash literal.
- Layout/FirstHashElementLineBreakChecks for a line break before the first element in a multi-line hash.
- Layout/FirstMethodArgumentLineBreakChecks for a line break before the first argument in a multi-line method call.
- Layout/FirstMethodParameterLineBreakChecks for a line break before the first parameter in a multi-line method parameter definition.
- Layout/FirstParameterIndentationChecks the indentation of the first parameter in a method definition.
- Layout/HashAlignmentAlign the elements of a hash literal if they span more than one line.
- Layout/HeredocArgumentClosingParenthesisChecks for the placement of the closing parenthesis in a method call that passes a HEREDOC string as an argument.
- Layout/HeredocIndentationChecks the indentation of the here document bodies.
- Layout/IndentationConsistencyKeep indentation straight.
- Layout/IndentationStyleConsistent indentation either with tabs only or spaces only.
- Layout/IndentationWidthUse 2 spaces for indentation.
- Layout/InitialIndentationChecks the indentation of the first non-blank non-comment line in a file.
- Layout/LeadingCommentSpaceComments should start with a space.
- Layout/LeadingEmptyLinesChecks for unnecessary blank lines at the beginning of a file.
- Layout/LineContinuationLeadingSpaceUse trailing spaces instead of leading spaces in strings broken over multiple lines (by a backslash).
- Layout/LineContinuationSpacingChecks the spacing in front of backslash in line continuations.
- Layout/LineEndStringConcatenationIndentationChecks the indentation of the next line after a line that ends with a string literal and a backslash.
- Layout/LineLengthChecks that line length does not exceed the configured limit.
- Layout/MultilineArrayBraceLayoutChecks that the closing brace in an array literal is either on the same line as the last array element, or a new line.
- Layout/MultilineArrayLineBreaksChecks that each item in a multi-line array literal starts on a separate line.
- Layout/MultilineAssignmentLayoutChecks for a newline after the assignment operator in multi-line assignments.
- Layout/MultilineBlockLayoutEnsures newlines after multiline block do statements.
- Layout/MultilineHashBraceLayoutChecks that the closing brace in a hash literal is either on the same line as the last hash element, or a new line.
- Layout/MultilineHashKeyLineBreaksChecks that each item in a multi-line hash literal starts on a separate line.
- Layout/MultilineMethodArgumentLineBreaksChecks that each argument in a multi-line method call starts on a separate line.
- Layout/MultilineMethodCallBraceLayoutChecks that the closing brace in a method call is either on the same line as the last method argument, or a new line.
- Layout/MultilineMethodCallIndentationChecks indentation of method calls with the dot operator that span more than one line.
- Layout/MultilineMethodDefinitionBraceLayoutChecks that the closing brace in a method definition is either on the same line as the last method parameter, or a new line.
- Layout/MultilineMethodParameterLineBreaksChecks that each parameter in a multi-line method definition starts on a separate line.
- Layout/MultilineOperationIndentationChecks indentation of binary operations that span more than one line.
- Layout/ParameterAlignmentAlign the parameters of a method definition if they span more than one line.
- Layout/RedundantLineBreakDo not break up an expression into multiple lines when it fits on a single line.
- Layout/RescueEnsureAlignmentAlign rescues and ensures correctly.
- Layout/SingleLineBlockChainPut method call on a separate line if chained to a single line block.
- Layout/SpaceAfterColonUse spaces after colons.
- Layout/SpaceAfterCommaUse spaces after commas.
- Layout/SpaceAfterMethodNameDo not put a space between a method name and the opening parenthesis in a method definition.
- Layout/SpaceAfterNotTracks redundant space after the ! operator.
- Layout/SpaceAfterSemicolonUse spaces after semicolons.
- Layout/SpaceAroundBlockParametersChecks the spacing inside and after block parameters pipes.
- Layout/SpaceAroundEqualsInParameterDefaultChecks that the equals signs in parameter default assignments have or don't have surrounding space depending on configuration.
- Layout/SpaceAroundKeywordUse a space around keywords if appropriate.
- Layout/SpaceAroundMethodCallOperatorChecks method call operators to not have spaces around them.
- Layout/SpaceAroundOperatorsUse a single space around operators.
- Layout/SpaceBeforeBlockBracesChecks that the left block brace has or doesn't have space before it.
- Layout/SpaceBeforeBracketsChecks for receiver with a space before the opening brackets.
- Layout/SpaceBeforeCommaNo spaces before commas.
- Layout/SpaceBeforeCommentChecks for missing space between code and a comment on the same line.
- Layout/SpaceBeforeFirstArgChecks that exactly one space is used between a method name and the first argument for method calls without parentheses.
- Layout/SpaceBeforeSemicolonNo spaces before semicolons.
- Layout/SpaceInLambdaLiteralChecks for spaces in lambda literals.
- Layout/SpaceInsideArrayLiteralBracketsChecks the spacing inside array literal brackets.
- Layout/SpaceInsideArrayPercentLiteralNo unnecessary additional spaces between elements in %i/%w literals.
- Layout/SpaceInsideBlockBracesChecks that block braces have or don't have surrounding space. For blocks taking parameters, checks that the left brace has or doesn't have trailing space.
- Layout/SpaceInsideHashLiteralBracesUse spaces inside hash literal braces - or don't.
- Layout/SpaceInsideParensNo spaces after ( or before ).
- Layout/SpaceInsidePercentLiteralDelimitersNo unnecessary spaces inside delimiters of %i/%w/%x literals.
- Layout/SpaceInsideRangeLiteralNo spaces inside range literals.
- Layout/SpaceInsideReferenceBracketsChecks the spacing inside referential brackets.
- Layout/SpaceInsideStringInterpolationChecks for padding/surrounding spaces inside string interpolation.
- Layout/TrailingEmptyLinesChecks trailing blank lines and final newline.
- Layout/TrailingWhitespaceAvoid trailing whitespace.
Lint 160
- Lint/AmbiguousAssignmentChecks for mistyped shorthand assignments.
- Lint/AmbiguousBlockAssociationChecks for ambiguous block association with method when param passed without parentheses.
- Lint/AmbiguousOperatorChecks for ambiguous operators in the first argument of a method invocation without parentheses.
- Lint/AmbiguousOperatorPrecedenceChecks for expressions containing multiple binary operations with ambiguous precedence.
- Lint/AmbiguousRangeChecks for ranges with ambiguous boundaries.
- Lint/AmbiguousRegexpLiteralChecks for ambiguous regexp literals in the first argument of a method invocation without parentheses.
- Lint/ArgumentMismatchChecks for calls that pass the wrong number of positional arguments to a method, using the project index.
- Lint/ArrayLiteralInRegexpChecks for an array literal interpolated inside a regexp.
- Lint/AssignmentInConditionDon't use assignment in conditions.
- Lint/BigDecimalNew
BigDecimal.new()is deprecated. UseBigDecimal()instead. - Lint/BinaryOperatorWithIdenticalOperandsChecks for places where binary operator has identical operands.
- Lint/BooleanSymbolChecks for
:trueand:falsesymbols. - Lint/CircularArgumentReferenceDefault values in optional keyword arguments and optional ordinal arguments should not refer back to the name of the argument.
- Lint/ConstantDefinitionInBlockDo not define constants within a block.
- Lint/ConstantOverwrittenInRescueChecks for overwriting an exception with an exception result by use
rescue =>. - Lint/ConstantReassignmentChecks for constant reassignments.
- Lint/ConstantResolutionChecks that constants are fully qualified with
::. - Lint/CopDirectiveSyntaxChecks that
# rubocop:directives are strictly formatted. - Lint/DataDefineOverrideDisallow overriding the
Databuilt-in methods viaData.define. - Lint/DebuggerChecks for debugger calls.
- Lint/DeprecatedClassMethodsChecks for deprecated class method calls.
- Lint/DeprecatedConstantsChecks for deprecated constants.
- Lint/DeprecatedOpenSSLConstantDon't use algorithm constants for
OpenSSL::CipherandOpenSSL::Digest. - Lint/DeprecatedReferenceChecks for references to methods and constants documented as deprecated with a YARD
@deprecatedtag. RequiresAllCops/UseProjectIndexto be enabled. - Lint/DisjunctiveAssignmentInConstructorIn constructor, plain assignment is preferred over disjunctive.
- Lint/DuplicateBranchChecks that there are no repeated bodies within
if/unless,case-whenandrescueconstructs. - Lint/DuplicateCaseConditionDo not repeat values in case conditionals.
- Lint/DuplicateElsifConditionDo not repeat conditions used in if
elsif. - Lint/DuplicateHashKeyChecks for duplicate keys in hash literals.
- Lint/DuplicateMagicCommentChecks for duplicated magic comments.
- Lint/DuplicateMatchPatternDo not repeat patterns in
inkeywords. - Lint/DuplicateMethodsChecks for duplicate method definitions.
- Lint/DuplicateRegexpCharacterClassElementChecks for duplicate elements in Regexp character classes.
- Lint/DuplicateRequireChecks for duplicate
requires andrequire_relatives. - Lint/DuplicateRescueExceptionChecks that there are no repeated exceptions used in
rescueexpressions. - Lint/DuplicateSetElementChecks for duplicate elements in Set.
- Lint/EachWithObjectArgumentChecks for immutable argument given to each_with_object.
- Lint/ElseLayoutChecks for odd code arrangement in an else block.
- Lint/EmptyBlockChecks for blocks without a body.
- Lint/EmptyClassChecks for classes and metaclasses without a body.
- Lint/EmptyConditionalBodyChecks for the presence of
if,elsifandunlessbranches without a body. - Lint/EmptyEnsureChecks for empty ensure block.
- Lint/EmptyExpressionChecks for empty expressions.
- Lint/EmptyFileEnforces that Ruby source files are not empty.
- Lint/EmptyInPatternChecks for the presence of
inpattern branches without a body. - Lint/EmptyInterpolationChecks for empty string interpolation.
- Lint/EmptyWhenChecks for
whenbranches with empty bodies. - Lint/EnsureReturnDo not use return in an ensure block.
- Lint/ErbNewArgumentsUse
:trim_modeand:eoutvarkeyword arguments toERB.new. - Lint/FlipFlopChecks for flip-flops.
- Lint/FloatComparisonChecks for the presence of precise comparison of floating point numbers.
- Lint/FloatOutOfRangeCatches floating-point literals too large or small for Ruby to represent.
- Lint/FormatParameterMismatchChecks for a mismatch between the format fields and the arguments to
format/sprintf/%. - Lint/HashCompareByIdentityPrefer using
Hash#compare_by_identitythan usingobject_idfor keys. - Lint/HashNewWithKeywordArgumentsAsDefaultChecks for the deprecated use of keyword arguments for hash default in
Hash.new. - Lint/HeredocMethodCallPositionChecks for the ordering of a method call where the receiver of the call is a HEREDOC.
- Lint/IdentityComparisonPrefer
equal?over==when comparingobject_id. - Lint/ImplicitStringConcatenationChecks for adjacent string literals on the same line, which could better be represented as a single string literal.
- Lint/IncompatibleIoSelectWithFiberSchedulerChecks for
IO.selectthat is incompatible with Fiber Scheduler. - Lint/IneffectiveAccessModifierChecks for attempts to use
privateorprotectedto set the visibility of a class method, which does not work. - Lint/InheritExceptionAvoid inheriting from the
Exceptionclass. - Lint/InterpolationCheckChecks for interpolation in a single quoted string.
- Lint/ItWithoutArgumentsInBlockChecks uses of
itcalls without arguments in block. - Lint/LambdaWithoutLiteralBlockChecks uses of lambda without a literal block.
- Lint/LiteralAsConditionChecks of literals used in conditions.
- Lint/LiteralAssignmentInConditionChecks for literal assignments in the conditions.
- Lint/LiteralInInterpolationChecks for literals used in interpolation.
- Lint/LoopUse Kernel#loop with break rather than begin/end/until or begin/end/while for post-loop tests.
- Lint/MisplacedMagicCommentChecks for magic comments placed where Ruby silently ignores them.
- Lint/MissingCopEnableDirectiveChecks for a
# rubocop:enableafter# rubocop:disable. - Lint/MissingSuperChecks for the presence of constructors and lifecycle callbacks without calls to
super. - Lint/MixedCaseRangeChecks for mixed-case character ranges since they include likely unintended characters.
- Lint/MixedRegexpCaptureTypesDo not mix named captures and numbered captures in a Regexp literal.
- Lint/MultipleComparisonUse
&&operator to compare multiple values. - Lint/NameTypoChecks for probable typos in constant and method names, using the project index.
- Lint/NestedMethodDefinitionDo not use nested method definitions.
- Lint/NestedPercentLiteralChecks for nested percent literals.
- Lint/NextWithoutAccumulatorDo not omit the accumulator when calling
nextin areduce/injectblock. - Lint/NoReturnInBeginEndBlocksDo not
returninsidebegin..endblocks in assignment contexts. - Lint/NonAtomicFileOperationChecks for non-atomic file operations.
- Lint/NonDeterministicRequireOrderAlways sort arrays returned by Dir.glob when requiring files.
- Lint/NonLocalExitFromIteratorDo not use return in iterator to cause non-local exit.
- Lint/NumberConversionChecks unsafe usage of number conversion methods.
- Lint/NumberedParameterAssignmentChecks for uses of numbered parameter assignment.
- Lint/NumericOperationWithConstantResultChecks for numeric operations with constant results.
- Lint/OrAssignmentToConstantChecks unintended or-assignment to constant.
- Lint/OrderedMagicCommentsChecks the proper ordering of magic comments and whether a magic comment is not placed before a shebang.
- Lint/OutOfRangeRegexpRefChecks for out of range reference for Regexp because it always returns nil.
- Lint/ParenthesesAsGroupedExpressionChecks for method calls with a space before the opening parenthesis.
- Lint/PercentStringArrayChecks for unwanted commas and quotes in %w/%W literals.
- Lint/PercentSymbolArrayChecks for unwanted commas and colons in %i/%I literals.
- Lint/RaiseExceptionChecks for
raiseorfailstatements which are raisingExceptionclass. - Lint/RandOneChecks for
rand(1)calls. Such calls always return0and most likely a mistake. - Lint/RedundantCopDisableDirectiveChecks for rubocop:disable comments that can be removed. Note: this cop is not disabled when disabling all cops. It must be explicitly disabled.
- Lint/RedundantCopEnableDirectiveChecks for rubocop:enable comments that can be removed.
- Lint/RedundantDirGlobSortChecks for redundant
sortmethod toDir.globandDir[]. - Lint/RedundantRegexpQuantifiersChecks for redundant quantifiers in Regexps.
- Lint/RedundantRequireStatementChecks for unnecessary
requirestatement. - Lint/RedundantSafeNavigationChecks for redundant safe navigation calls.
- Lint/RedundantSplatExpansionChecks for splat unnecessarily being called on literals.
- Lint/RedundantStringCoercionChecks for Object#to_s usage in string interpolation.
- Lint/RedundantTypeConversionChecks for redundantly converting a literal to the same type.
- Lint/RedundantWithIndexChecks for redundant
with_index. - Lint/RedundantWithObjectChecks for redundant
with_object. - Lint/RefinementImportMethodsUse
Refinement#import_methodswhen usingincludeorprependinrefineblock. - Lint/RegexpAsConditionDo not use regexp literal as a condition. The regexp literal matches
$_implicitly. - Lint/RequireParenthesesUse parentheses in the method call to avoid confusion about precedence.
- Lint/RequireRangeParenthesesChecks that a range literal is enclosed in parentheses when the end of the range is at a line break.
- Lint/RequireRelativeSelfPathChecks for uses a file requiring itself with
require_relative. - Lint/RescueExceptionAvoid rescuing the Exception class.
- Lint/RescueTypeAvoid rescuing from non constants that could result in a
TypeError. - Lint/ReturnInVoidContextChecks for return in void context.
- Lint/SafeNavigationChainDo not chain ordinary method call after safe navigation operator.
- Lint/SafeNavigationConsistencyCheck to make sure that if safe navigation is used in an
&&or||condition, consistent and appropriate safe navigation, without excess or deficiency, is used for all method calls on the same object. - Lint/SafeNavigationWithEmptyAvoid
foo&.empty?in conditionals. - Lint/ScriptPermissionGrant script file execute permission.
- Lint/SelfAssignmentChecks for self-assignments.
- Lint/SendWithMixinArgumentChecks for
sendmethod when using mixin. - Lint/ShadowedArgumentAvoid reassigning arguments before they were used.
- Lint/ShadowedExceptionAvoid rescuing a higher level exception before a lower level exception.
- Lint/ShadowingOuterLocalVariableDo not use the same name as outer local variable for block arguments or block local variables.
- Lint/SharedMutableDefaultChecks for mutable literals used as default arguments during Hash initialization.
- Lint/StructNewOverrideDisallow overriding the
Structbuilt-in methods viaStruct.new. - Lint/SuperArgumentMismatchChecks for
supercalls that pass the wrong number of positional arguments to the overridden implementation, using the project index. - Lint/SuppressedExceptionDon't suppress exceptions.
- Lint/SuppressedExceptionInNumberConversionChecks for cases where exceptions unrelated to the numeric constructors may be unintentionally swallowed.
- Lint/SymbolConversionChecks for unnecessary symbol conversions.
- Lint/SyntaxChecks for syntax errors.
- Lint/ToEnumArgumentsEnsures that
to_enum/enum_for, called for the current method, has correct arguments. - Lint/ToJSONEnsure #to_json includes an optional argument.
- Lint/TopLevelReturnWithArgumentDetects top level return statements with argument.
- Lint/TrailingCommaInAttributeDeclarationChecks for trailing commas in attribute declarations.
- Lint/TripleQuotesChecks for useless triple quote constructs.
- Lint/UnderscorePrefixedVariableNameDo not use prefix
_for a variable that is used. - Lint/UnescapedBracketInRegexpChecks for unescaped literal
]in Regexp. - Lint/UnexpectedBlockArityLooks for blocks that have fewer arguments that the calling method expects.
- Lint/UnifiedIntegerUse Integer instead of Fixnum or Bignum.
- Lint/UnmodifiedReduceAccumulatorChecks for
reduceorinjectblocks that do not update the accumulator each iteration. - Lint/UnreachableCodeChecks for unreachable code.
- Lint/UnreachableLoopChecks for loops that will have at most one iteration.
- Lint/UnreachablePatternBranchChecks for unreachable
inpattern branches after an unconditional catch-all pattern. - Lint/UnusedBlockArgumentChecks for unused block arguments.
- Lint/UnusedMethodArgumentChecks for unused method arguments.
- Lint/UnusedPrivateMethodChecks for private instance methods that are not referenced anywhere in the project. Requires
AllCops/UseProjectIndexto be enabled. - Lint/UriEscapeUnescape
URI.escapemethod is obsolete and should not be used. Instead, useCGI.escape,URI.encode_www_formorURI.encode_www_form_componentdepending on your specific use case. AlsoURI.unescapemethod is obsolete and should not be used. Instead, useCGI.unescape,URI.decode_www_formorURI.decode_www_form_componentdepending on your specific use case. - Lint/UriRegexpUse
URI::DEFAULT_PARSER.make_regexpinstead ofURI.regexp. - Lint/UselessAccessModifierChecks for useless access modifiers.
- Lint/UselessAssignmentChecks for useless assignment to a local variable.
- Lint/UselessConstantScopingChecks for useless constant scoping.
- Lint/UselessDefaultValueArgumentChecks for usage of
fetchorArray.newwith default value argument and block. - Lint/UselessDefinedChecks for calls to
defined?with strings and symbols. The result of such a call will always be truthy. - Lint/UselessElseWithoutRescueChecks for useless
elseinbegin..endwithoutrescue. - Lint/UselessMethodDefinitionChecks for useless method definitions.
- Lint/UselessNumericOperationChecks for useless numeric operations.
- Lint/UselessOrChecks for useless OR expressions.
- Lint/UselessRescueChecks for useless
rescues. - Lint/UselessRuby2KeywordsFinds unnecessary uses of
ruby2_keywords. - Lint/UselessSetterCallChecks for useless setter call to a local variable.
- Lint/UselessTimesChecks for useless
Integer#timescalls. - Lint/VoidChecks for operators, literals, lambdas, and procs used in void context.
Metrics 10
- Metrics/AbcSizeChecks that the ABC size of methods is not higher than the configured maximum.
- Metrics/BlockLengthAvoid long blocks with many lines.
- Metrics/BlockNestingAvoid excessive block nesting.
- Metrics/ClassLengthAvoid classes longer than 100 lines of code.
- Metrics/CollectionLiteralLengthChecks for
ArrayorHashliterals with many entries. - Metrics/CyclomaticComplexityChecks that the cyclomatic complexity of methods is not higher than the configured maximum.
- Metrics/MethodLengthAvoid methods longer than 10 lines of code.
- Metrics/ModuleLengthAvoid modules longer than 100 lines of code.
- Metrics/ParameterListsAvoid parameter lists longer than three or four parameters.
- Metrics/PerceivedComplexityChecks that the perceived complexity of methods is not higher than the configured maximum.
Migration 1
- Migration/DepartmentNameChecks that cop names in
rubocop:disable(etc.) comments are given with a department name.
Naming 19
- Naming/AccessorMethodNameChecks the naming of accessor methods for get_/set_.
- Naming/AsciiIdentifiersUse only ascii symbols in identifiers and constants.
- Naming/BinaryOperatorParameterNameChecks that the sole parameter of binary operator methods is named
other. - Naming/BlockForwardingUse anonymous block forwarding.
- Naming/BlockParameterNameChecks for block parameter names that contain capital letters, end in numbers, or do not meet a minimal length.
- Naming/ClassAndModuleCamelCaseUse CamelCase for classes and modules.
- Naming/ConstantNameConstants should use SCREAMING_SNAKE_CASE.
- Naming/FileNameUse snake_case for source file names.
- Naming/HeredocDelimiterCaseUse configured case for heredoc delimiters.
- Naming/HeredocDelimiterNamingUse descriptive heredoc delimiters.
- Naming/InclusiveLanguageRecommend the use of inclusive language instead of problematic terms.
- Naming/MemoizedInstanceVariableNameMemoized method name should match memo instance variable name.
- Naming/MethodNameUse the configured style when naming methods.
- Naming/MethodParameterNameChecks for method parameter names that contain capital letters, end in numbers, or do not meet a minimal length.
- Naming/PredicateMethodChecks that predicate methods end with
?and non-predicate methods do not. - Naming/PredicatePrefixChecks that predicate method names end with a question mark and do not start with a forbidden prefix.
- Naming/RescuedExceptionsVariableNameUse consistent rescued exceptions variables naming.
- Naming/VariableNameUse the configured style when naming variables.
- Naming/VariableNumberUse the configured style when numbering symbols, methods and variables.
Security 7
- Security/CompoundHashChecks for
hashimplementations that combine values manually instead of delegating toArray#hash. - Security/EvalChecks for the use of
Kernel#evalandBinding#evalwith dynamic arguments. - Security/IoMethodsChecks for the first argument to
IO.read,IO.binread,IO.write,IO.binwrite,IO.foreach, andIO.readlines. - Security/JSONLoadPrefer usage of
JSON.parseoverJSON.loaddue to potential security issues. See reference for more information. - Security/MarshalLoadAvoid using of
Marshal.loadorMarshal.restoredue to potential security issues. See reference for more information. - Security/OpenChecks for the use of
Kernel#openandURI.openwith dynamic data. - Security/YAMLLoadPrefer usage of
YAML.safe_loadoverYAML.loaddue to potential security issues. See reference for more information.
Style 299
- Style/AccessModifierDeclarationsChecks style of how access modifiers are used.
- Style/AccessorGroupingChecks for grouping of accessors in
classandmodulebodies. - Style/AliasUse alias instead of alias_method.
- Style/AmbiguousEndlessMethodDefinitionChecks for endless methods inside operators of lower precedence.
- Style/AndOrUse &&/|| instead of and/or.
- Style/ArgumentsForwardingUse arguments forwarding.
- Style/ArrayCoercionUse Array() instead of explicit Array check or [*var], when dealing with a variable you want to treat as an Array, but you're not certain it's an array.
- Style/ArrayFirstLastUse
arr.firstandarr.lastinstead ofarr[0]andarr[-1]. - Style/ArrayIntersectUse
array1.intersect?(array2)instead of(array1 & array2).any?. - Style/ArrayIntersectWithSingleElementUse
include?(element)instead ofintersect?([element]). - Style/ArrayJoinUse Array#join instead of Array#*.
- Style/AsciiCommentsUse only ascii symbols in comments.
- Style/AttrChecks for uses of Module#attr.
- Style/AutoResourceCleanupSuggests the usage of an auto resource cleanup version of a method (if available).
- Style/BarePercentLiteralsChecks if usage of %() or %Q() matches configuration.
- Style/BeginBlockAvoid the use of BEGIN blocks.
- Style/BisectedAttrAccessorChecks for places where
attr_readerandattr_writerfor the same method can be combined into singleattr_accessor. - Style/BitwisePredicatePrefer bitwise predicate methods over direct comparison operations.
- Style/BlockCommentsDo not use block comments.
- Style/BlockDelimitersAvoid using {...} for multi-line blocks (multiline chaining is always ugly). Prefer {...} over do...end for single-line blocks.
- Style/CaseEqualityAvoid explicit use of the case equality operator (
===). - Style/CaseLikeIfIdentifies places where
if-elsifconstructions can be replaced withcase-when. - Style/CharacterLiteralChecks for uses of character literals.
- Style/ClassAndModuleChildrenChecks style of children classes and modules.
- Style/ClassCheckEnforces consistent use of
Object#is_a?orObject#kind_of?. - Style/ClassEqualityComparisonEnforces the use of
Object#instance_of?instead of class comparison for equality. - Style/ClassMethodsUse self when defining module/class methods.
- Style/ClassMethodsDefinitionsEnforces using
def self.method_nameorclass << selfto define class methods. - Style/ClassVarsAvoid the use of class variables.
- Style/CollectionCompactUse
{Array,Hash}#{compact,compact!}instead of custom logic to reject nils. - Style/CollectionMethodsEnforces the use of consistent method names from the
Enumerablemodule. - Style/CollectionQueryingPrefer
Enumerablepredicate methods over expressions withcount. - Style/ColonMethodCallDo not use :: for method call.
- Style/ColonMethodDefinitionDo not use :: for defining class methods.
- Style/CombinableDefinedChecks successive
defined?calls that can be combined into a single call. - Style/CombinableLoopsChecks for places where multiple consecutive loops over the same data can be combined into a single loop.
- Style/CommandLiteralUse `` or %x around command literals.
- Style/CommentAnnotationChecks formatting of special comments (TODO, FIXME, OPTIMIZE, HACK, REVIEW, NOTE).
- Style/CommentedKeywordDo not place comments on the same line as certain keywords.
- Style/ComparableBetweenEnforces the use of
Comparable#between?instead of logical comparison. - Style/ComparableClampEnforces the use of
Comparable#clampinstead of comparison by minimum and maximum. - Style/ConcatArrayLiteralsEnforces the use of
Array#push(item)instead ofArray#concat([item])to avoid redundant array literals. - Style/ConditionalAssignmentUse the return value of
ifandcasestatements for assignment to a variable and variable comparison instead of assigning that variable inside of each branch. - Style/ConstantVisibilityCheck that class- and module constants have visibility declarations.
- Style/CopyrightInclude a copyright notice in each file before any code.
- Style/DataInheritanceChecks for inheritance from Data.define.
- Style/DateTimeUse Time over DateTime.
- Style/DefWithParenthesesUse def with parentheses when there are arguments.
- Style/DigChainUse
digwith multiple parameters instead of chaining multiple calls. - Style/DirUse the
__dir__method to retrieve the canonicalized absolute path to the current file. - Style/DirEmptyPrefer to use
Dir.empty?('path/to/dir')when checking if a directory is empty. - Style/DirectiveScopeChecks for directive scopes that can be expressed with the tighter
disable-nextform. - Style/DisableCopsWithinSourceCodeDirectiveForbids disabling/enabling cops within source code.
- Style/DocumentDynamicEvalDefinitionWhen using
class_eval(or othereval) with string interpolation, add a comment block showing its appearance if interpolated. - Style/DocumentationDocument classes and non-namespace modules.
- Style/DocumentationMethodChecks for missing documentation comment for public methods.
- Style/DoubleNegationChecks for uses of double negation (!!).
- Style/EachForSimpleLoopUse
Integer#timesfor a simple loop which iterates a fixed number of times. - Style/EachWithObjectPrefer
each_with_objectoverinjectorreduce. - Style/EmptyBlockParameterOmit pipes for empty block parameters.
- Style/EmptyCaseConditionAvoid empty condition in case statements.
- Style/EmptyClassDefinitionEnforces consistent style for empty class definitions.
- Style/EmptyElseAvoid empty else-clauses.
- Style/EmptyHeredocChecks for using empty heredoc to reduce redundancy.
- Style/EmptyLambdaParameterOmit parens for empty lambda parameters.
- Style/EmptyLiteralPrefer literals to Array.new/Hash.new/String.new.
- Style/EmptyMethodChecks the formatting of empty method definitions.
- Style/EmptyStringInsideInterpolationChecks for empty strings being assigned inside string interpolation.
- Style/EncodingUse UTF-8 as the source file encoding.
- Style/EndBlockAvoid the use of END blocks.
- Style/EndlessMethodAvoid the use of multi-lined endless method definitions.
- Style/EnvHomeChecks for consistent usage of
ENV['HOME']. - Style/EvalWithLocationPass
__FILE__and__LINE__toevalmethod, as they are used by backtraces. - Style/EvenOddFavor the use of
Integer#even?&&Integer#odd?. - Style/ExactRegexpMatchChecks for exact regexp match inside Regexp literals.
- Style/ExpandPathArgumentsUse
expand_path(__dir__)instead ofexpand_path('..', __FILE__). - Style/ExplicitBlockArgumentConsider using explicit block argument to avoid writing block literal that just passes its arguments to another block.
- Style/ExponentialNotationEnforces consistency in the use of exponential (scientific) notation.
- Style/FetchEnvVarSuggests
ENV.fetchfor the replacement ofENV[]. - Style/FileEmptyPrefer to use
File.empty?('path/to/file')when checking if a file is empty. - Style/FileNullUse
File::NULLinstead of hardcoding "dev/null". - Style/FileOpenChecks for
File.openwithout a block, which can leak file descriptors. - Style/FileReadFavor
File.(bin)readconvenience methods. - Style/FileTouchFavor
FileUtils.touchfor touching files. - Style/FileWriteFavor
File.(bin)writeconvenience methods. - Style/FloatDivisionFor performing float division, coerce one side only.
- Style/ForChecks use of for or each in multiline loops.
- Style/FormatStringEnforce the use of Kernel#sprintf, Kernel#format or String#%.
- Style/FormatStringTokenUse a consistent style for format string tokens.
- Style/FrozenStringLiteralCommentAdd the frozen_string_literal comment to the top of files to help transition to frozen string literals by default.
- Style/GlobalStdStreamEnforces the use of
$stdout/$stderr/$stdininstead ofSTDOUT/STDERR/STDIN. - Style/GlobalVarsDo not introduce global variables.
- Style/GuardClauseChecks for conditionals that can be replaced with guard clauses.
- Style/HashAsLastArrayItemChecks for presence or absence of braces around hash literal as a last array item depending on configuration.
- Style/HashConversionAvoid Hash[] in favor of ary.to_h or literal hashes.
- Style/HashEachMethodsUse Hash#each_key and Hash#each_value.
- Style/HashExceptChecks for usages of
Hash#reject,Hash#select, andHash#filtermethods that can be replaced withHash#exceptmethod. - Style/HashFetchChainUse
Hash#diginstead of chainedfetchcalls. - Style/HashLikeCaseChecks for places where
case-whenrepresents a simple 1:1 mapping and can be replaced with a hash lookup. - Style/HashLookupMethodEnforces the use of either
Hash#[]orHash#fetchfor hash lookup. - Style/HashSliceChecks for usages of
Hash#reject,Hash#select, andHash#filtermethods that can be replaced withHash#slicemethod. - Style/HashSyntaxPrefer Ruby 1.9 hash syntax { a: 1, b: 2 } over 1.8 syntax { :a => 1, :b => 2 }.
- Style/HashTransformKeysPrefer
transform_keysovereach_with_object,map, orto_h. - Style/HashTransformValuesPrefer
transform_valuesovereach_with_object,map, orto_h. - Style/IdenticalConditionalBranchesChecks that conditional statements do not have an identical line at the end of each branch, which can validly be moved out of the conditional.
- Style/IfInsideElseFinds if nodes inside else, which can be converted to elsif.
- Style/IfUnlessModifierFavor modifier if/unless usage when you have a single-line body.
- Style/IfUnlessModifierOfIfUnlessAvoid modifier if/unless usage on conditionals.
- Style/IfWithBooleanLiteralBranchesChecks for redundant
ifwith boolean literal branches. - Style/IfWithSemicolonDo not use if x; .... Use the ternary operator instead.
- Style/ImplicitRuntimeErrorUse
raiseorfailwith an explicit exception class and message, rather than just a message. - Style/InPatternThenChecks for
in;uses incaseexpressions. - Style/InfiniteLoopUse Kernel#loop for infinite loops. This cop is unsafe if the body may raise a
StopIterationexception. - Style/InlineCommentAvoid trailing inline comments.
- Style/InverseMethodsUse the inverse method instead of
!.methodif an inverse method is defined. - Style/InvertibleUnlessConditionFavor
ifwith inverted condition overunless. - Style/IpAddressesDon't include literal IP addresses in code.
- Style/ItAssignmentChecks for local variables and method parameters named
it. - Style/ItBlockParameterChecks for blocks with one argument where
itblock parameter can be used. - Style/KeywordArgumentsMergingWhen passing an existing hash as keyword arguments, provide additional arguments directly rather than using
merge. - Style/KeywordParametersOrderEnforces that optional keyword parameters are placed at the end of the parameters list.
- Style/LambdaUse the new lambda literal syntax for single-line blocks.
- Style/LambdaCallUse lambda.call(...) instead of lambda.(...).
- Style/LineEndConcatenationUse \ instead of + or << to concatenate two string literals at line end.
- Style/MagicCommentFormatUse a consistent style for magic comments.
- Style/MapCompactWithConditionalBlockPrefer
selectorrejectovermap { ... }.compact. - Style/MapIntoArrayChecks for usages of
eachwith<<,push, orappendwhich can be replaced bymap. - Style/MapJoinChecks for redundant
map(&:to_s)beforejoin. - Style/MapToHashPrefer
to_hwith a block overmap.to_h. - Style/MapToSetPrefer
to_setwith a block overmap.to_set. - Style/MethodCallWithArgsParenthesesUse parentheses for method calls with arguments.
- Style/MethodCallWithoutArgsParenthesesDo not use parentheses for method calls with no arguments.
- Style/MethodCalledOnDoEndBlockAvoid chaining a method call on a do...end block.
- Style/MethodDefParenthesesChecks if the method definitions have or don't have parentheses.
- Style/MinMaxUse
Enumerable#minmaxinstead ofEnumerable#minandEnumerable#maxin conjunction. - Style/MinMaxComparisonEnforces the use of
maxormininstead of comparison for greater or less. - Style/MissingElseRequire if/case expressions to have an else branches. If enabled, it is recommended that Style/UnlessElse and Style/EmptyElse be enabled. This will conflict with Style/EmptyElse if Style/EmptyElse is configured to style "both".
- Style/MissingRespondToMissingChecks if
method_missingis implemented without implementingrespond_to_missing. - Style/MixinGroupingChecks for grouping of mixins in
classandmodulebodies. - Style/MixinUsageChecks that
include,extendandprependexists at the top level. - Style/ModuleFunctionChecks for usage of
extend selfin modules. - Style/ModuleMemberExistenceCheckChecks for usage of
Modulemethods returning arrays that can be replaced with equivalent predicates. - Style/MultilineBlockChainAvoid multi-line chains of blocks.
- Style/MultilineIfModifierChecks for uses of
if/unlessmodifiers with multiline bodies. - Style/MultilineIfThenDo not use then for multi-line if/unless.
- Style/MultilineInPatternThenDo not use
thenfor multi-lineinstatement. - Style/MultilineMemoizationWrap multiline memoizations in a
beginandendblock. - Style/MultilineMethodSignatureAvoid multi-line method signatures.
- Style/MultilineTernaryOperatorAvoid multi-line ?: (the ternary operator); use if/unless instead.
- Style/MultilineWhenThenDo not use then for multi-line when statement.
- Style/MultipleComparisonAvoid comparing a variable with multiple items in a conditional, use Array#include? instead.
- Style/MutableConstantDo not assign mutable objects to constants.
- Style/NegatedIfFavor unless over if for negative conditions (or control flow or).
- Style/NegatedIfElseConditionChecks for uses of
if-elseand ternary operators with a negated condition which can be simplified by inverting condition and swapping branches. - Style/NegatedUnlessFavor if over unless for negative conditions.
- Style/NegatedWhileFavor until over while for negative conditions.
- Style/NegativeArrayIndexUse negative array indices instead of calculating array length minus a value. Also handles range patterns with length calculations. Recognizes preserving methods and their combinations, allowing safe replacement when the receiver matches.
- Style/NestedFileDirnameChecks for nested
File.dirname. - Style/NestedModifierAvoid using nested modifiers.
- Style/NestedParenthesizedCallsParenthesize method calls which are nested inside the argument list of another parenthesized method call.
- Style/NestedTernaryOperatorUse one expression per branch in a ternary operator.
- Style/NextUse
nextto skip iteration instead of a condition at the end. - Style/NilComparisonPrefer x.nil? to x == nil.
- Style/NilLambdaPrefer
-> {}to-> { nil }. - Style/NonNilCheckChecks for redundant nil checks.
- Style/NotUse ! instead of not.
- Style/NumberedParametersRestrict the usage of numbered parameters.
- Style/NumberedParametersLimitAvoid excessive numbered params in a single block.
- Style/NumericLiteralPrefixUse smallcase prefixes for numeric literals.
- Style/NumericLiteralsAdd underscores to large numeric literals to improve their readability.
- Style/NumericPredicateChecks for the use of predicate- or comparison methods for numeric comparisons.
- Style/ObjectThenEnforces the use of consistent method names
Object#yield_selforObject#then. - Style/OneClassPerFileChecks that each source file defines at most one top-level class or module.
- Style/OneLineConditionalFavor the ternary operator (?:) or multi-line constructs over single-line if/then/else/end constructs.
- Style/OpenStructUseAvoid using OpenStruct. As of Ruby 3.0, use is officially discouraged due to performance, version compatibility, and potential security issues.
- Style/OperatorMethodCallChecks for redundant dot before operator method call.
- Style/OptionHashDon't use option hashes when you can use keyword arguments.
- Style/OptionalArgumentsChecks for optional arguments that do not appear at the end of the argument list.
- Style/OptionalBooleanParameterUse keyword arguments when defining method with boolean argument.
- Style/OrAssignmentRecommend usage of double pipe equals (||=) where applicable.
- Style/ParallelAssignmentCheck for simple usages of parallel assignment. It will only warn when the number of variables matches on both sides of the assignment.
- Style/ParenthesesAroundConditionDon't use parentheses around the condition of an if/unless/while.
- Style/PartitionInsteadOfDoubleSelectChecks for consecutive
select/filter/find_allandrejectcalls on the same receiver with the same block body. - Style/PercentLiteralDelimitersUse
%-literal delimiters consistently. - Style/PercentQLiteralsChecks if uses of %Q/%q match the configured preference.
- Style/PerlBackrefsAvoid Perl-style regex back references.
- Style/PredicateWithKindPrefer
any?(Klass)toany? { |x| x.is_a?(Klass) }. - Style/PreferredHashMethodsChecks use of
has_key?andhas_value?Hash methods. - Style/ProcUse proc instead of Proc.new.
- Style/QuotedSymbolsUse a consistent style for quoted symbols.
- Style/RaiseArgsChecks the arguments passed to raise/fail.
- Style/RandomWithOffsetPrefer to use ranges when generating random numbers instead of integers with offsets.
- Style/ReduceToHashUse
to_h { ... }instead ofeach_with_object,inject, orreduceto build a hash. - Style/RedundantArgumentChecks for a redundant argument passed to certain methods.
- Style/RedundantArrayConstructorChecks for the instantiation of array using redundant
Arrayconstructor. - Style/RedundantArrayFlattenChecks for redundant calls of
Array#flatten. - Style/RedundantAssignmentChecks for redundant assignment before returning.
- Style/RedundantBeginDon't use begin blocks when they are not needed.
- Style/RedundantCapitalWChecks for %W when interpolation is not needed.
- Style/RedundantConditionChecks for unnecessary conditional expressions.
- Style/RedundantConditionalDon't return true/false from a conditional.
- Style/RedundantConstantBaseAvoid redundant
::prefix on constant. - Style/RedundantCurrentDirectoryInPathChecks for a redundant current directory in a path given to
require_relative. - Style/RedundantDoubleSplatHashBracesChecks for redundant uses of double splat hash braces.
- Style/RedundantEachChecks for redundant
each. - Style/RedundantExceptionChecks for an obsolete RuntimeException argument in raise/fail.
- Style/RedundantFetchBlockUse
fetch(key, value)instead offetch(key) { value }when value has Numeric, Rational, Complex, Symbol or String type,false,true,nilor is a constant. - Style/RedundantFileExtensionInRequireChecks for the presence of superfluous
.rbextension in the filename provided torequireandrequire_relative. - Style/RedundantFilterChainIdentifies usages of
any?,empty?,none?orone?predicate methods chained toselect/filter/find_alland change them to use predicate method instead. - Style/RedundantFormatChecks for usages of
Kernel#formatorKernel#sprintfwith only a single argument. - Style/RedundantFreezeChecks usages of Object#freeze on immutable objects.
- Style/RedundantHeredocDelimiterQuotesChecks for redundant heredoc delimiter quotes.
- Style/RedundantInitializeChecks for redundant
initializemethods. - Style/RedundantInterpolationChecks for strings that are just an interpolated expression.
- Style/RedundantInterpolationUnfreezeChecks for redundant unfreezing of interpolated strings.
- Style/RedundantLineContinuationChecks for redundant line continuation.
- Style/RedundantMinMaxByIdentifies places where
max_by/min_bycan be replaced bymax/min. - Style/RedundantParenthesesChecks for parentheses that seem not to serve any purpose.
- Style/RedundantPercentQChecks for %q/%Q when single quotes or double quotes would do.
- Style/RedundantRegexpArgumentIdentifies places where argument can be replaced from a deterministic regexp to a string.
- Style/RedundantRegexpCharacterClassChecks for unnecessary single-element Regexp character classes.
- Style/RedundantRegexpConstructorChecks for the instantiation of regexp using redundant
Regexp.neworRegexp.compile. - Style/RedundantRegexpEscapeChecks for redundant escapes in Regexps.
- Style/RedundantReturnDon't use return where it's not required.
- Style/RedundantSelfDon't use self where it's not needed.
- Style/RedundantSelfAssignmentChecks for places where redundant assignments are made for in place modification methods.
- Style/RedundantSelfAssignmentBranchChecks for places where conditional branch makes redundant self-assignment.
- Style/RedundantSortUse
mininstead ofsort.first,max_byinstead ofsort_by...last, etc. - Style/RedundantSortByUse
sortinstead ofsort_by { |x| x }. - Style/RedundantStringEscapeChecks for redundant escapes in string literals.
- Style/RedundantStructKeywordInitChecks for redundant
keyword_initoption forStruct.new. - Style/RegexpLiteralUse / or %r around regular expressions.
- Style/RequireOrderSort
requireandrequire_relativein alphabetical order. - Style/RescueModifierAvoid using rescue in its modifier form.
- Style/RescueStandardErrorAvoid rescuing without specifying an error class.
- Style/ReturnNilUse return instead of return nil.
- Style/ReturnNilInPredicateMethodDefinitionChecks if uses of
returnorreturn nilin predicate method definition. - Style/ReverseFindUse
array.rfindinstead ofarray.reverse.find. - Style/SafeNavigationTransforms usages of a method call safeguarded by a check for the existence of the object to safe navigation (
&.). Autocorrection is unsafe as it assumes the object will benilor truthy, but neverfalse. - Style/SafeNavigationChainLengthEnforces safe navigation chains length to not exceed the configured maximum.
- Style/SampleUse
sampleinstead ofshuffle.first,shuffle.last, andshuffle[Integer]. - Style/SelectByKindPrefer grep/grep_v to select/reject/find/detect with a kind check.
- Style/SelectByRangePrefer grep/grep_v to select/reject/find/detect with a range check.
- Style/SelectByRegexpPrefer grep/grep_v to select/reject/find/detect with a regexp match.
- Style/SelfAssignmentChecks for places where self-assignment shorthand should have been used.
- Style/SemicolonDon't use semicolons to terminate expressions.
- Style/SendPrefer
Object#__send__orObject#public_sendtosend, assendmay overlap with existing methods. - Style/SendWithLiteralMethodNameDetects the use of the
public_sendmethod with a static method name argument. - Style/SignalExceptionChecks for proper usage of fail and raise.
- Style/SingleArgumentDigAvoid using single argument dig method.
- Style/SingleLineBlockParamsEnforces the names of some block params.
- Style/SingleLineDoEndBlockChecks for single-line
do...endblocks. - Style/SingleLineMethodsAvoid single-line methods.
- Style/SlicingWithRangeChecks array slicing is done with redundant, endless, and beginless ranges when suitable.
- Style/SoleNestedConditionalFinds sole nested conditional nodes which can be merged into outer conditional node.
- Style/SpecialGlobalVarsAvoid Perl-style global variables.
- Style/StabbyLambdaParenthesesChecks for the usage of parentheses around stabby lambda arguments.
- Style/StaticClassPrefer modules to classes with only class methods.
- Style/StderrPutsUse
warninstead of$stderr.puts. - Style/StringCharsChecks for uses of
String#splitwith empty string or regexp literal argument. - Style/StringConcatenationChecks for places where string concatenation can be replaced with string interpolation.
- Style/StringHashKeysPrefer symbols instead of strings as hash keys.
- Style/StringLiteralsChecks if uses of quotes match the configured preference.
- Style/StringLiteralsInInterpolationChecks if uses of quotes inside expressions in interpolated strings match the configured preference.
- Style/StringMethodsChecks if configured preferred methods are used over non-preferred.
- Style/StripUse
stripinstead oflstrip.rstrip. - Style/StructInheritanceChecks for inheritance from Struct.new.
- Style/SuperArgumentsCall
superwithout arguments and parentheses when the signature is identical. - Style/SuperWithArgsParenthesesUse parentheses for
superwith arguments. - Style/SwapValuesEnforces the use of shorthand-style swapping of 2 variables.
- Style/SymbolArrayUse %i or %I for arrays of symbols.
- Style/SymbolLiteralUse plain symbols instead of string symbols when possible.
- Style/SymbolProcUse symbols as procs instead of blocks when possible.
- Style/TallyMethodPrefer
Enumerable#tallyover manual counting patterns. - Style/TernaryParenthesesChecks for use of parentheses around ternary conditions.
- Style/TimeNowPrefer
Time.nowoverTime.newwhen retrieving the current system time. - Style/TopLevelMethodDefinitionLooks for top-level method definitions.
- Style/TrailingBodyOnClassClass body goes below class statement.
- Style/TrailingBodyOnMethodDefinitionChecks for trailing code after the method definition.
- Style/TrailingBodyOnModuleChecks for trailing code after the module definition.
- Style/TrailingCommaInArgumentsChecks for trailing comma in argument lists.
- Style/TrailingCommaInArrayLiteralChecks for trailing comma in array literals.
- Style/TrailingCommaInBlockArgsChecks for useless trailing commas in block arguments.
- Style/TrailingCommaInHashLiteralChecks for trailing comma in hash literals.
- Style/TrailingMethodEndStatementChecks for trailing end statement on line of method body.
- Style/TrailingUnderscoreVariableChecks for the usage of unneeded trailing underscores at the end of parallel variable assignment.
- Style/TrivialAccessorsPrefer attr_* methods to trivial readers/writers.
- Style/UnlessElseDo not use unless with else. Rewrite these with the positive case first.
- Style/UnlessLogicalOperatorsChecks for use of logical operators in an unless condition.
- Style/UnpackFirstChecks for accessing the first element of
String#unpackinstead of usingunpack1. - Style/VariableInterpolationDon't interpolate global, instance and class variables directly in strings.
- Style/WhenThenUse when x then ... for one-line cases.
- Style/WhileUntilDoChecks for redundant do after while or until.
- Style/WhileUntilModifierFavor modifier while/until usage when you have a single-line body.
- Style/WordArrayUse %w or %W for arrays of words.
- Style/YAMLFileReadChecks for the use of
YAML.load,YAML.safe_load, andYAML.parsewithFile.readargument. - Style/YodaConditionForbid or enforce yoda conditions.
- Style/YodaExpressionForbid the use of yoda expressions.
- Style/ZeroLengthPredicateUse #empty? when testing for objects of length 0.
Capybara 6 rubocop-capybara 3.0.0
- Capybara/AmbiguousClickSpecify the exact target to click on.
- Capybara/AssertStyleChecks for usage of deprecated assert style method.
- Capybara/FindAllFirstEnforces use of
firstinstead ofallwithfirstor[0]. - Capybara/RedundantWithinFindChecks for redundant
within find(...)calls. - Capybara/SpecificActionsChecks for there is a more specific actions offered by Capybara.
- Capybara/SpecificFindersChecks if there is a more specific finder offered by Capybara.
Capybara/RSpec 9 rubocop-capybara 3.0.0
- Capybara/RSpec/CurrentPathExpectationChecks that no expectations are set on Capybara's
current_path. - Capybara/RSpec/HaveContentChecks for usage of
have_contentandhave_no_content. - Capybara/RSpec/HaveSelectorUse
have_cssorhave_xpathinstead ofhave_selector. - Capybara/RSpec/MatchStyleChecks for usage of deprecated style methods in RSpec matchers.
- Capybara/RSpec/NegationMatcherEnforces use of
have_no_*ornot_tofor negated expectations. - Capybara/RSpec/NegationMatcherAfterVisitDo not allow negative matchers to be used immediately after
visit. - Capybara/RSpec/PredicateMatcherPrefer using predicate matcher over using predicate method directly.
- Capybara/RSpec/SpecificMatcherChecks for there is a more specific matcher offered by Capybara.
- Capybara/RSpec/VisibilityMatcherChecks for boolean visibility in Capybara finders.
FactoryBot 11 rubocop-factory_bot 2.28.0
- FactoryBot/AssociationStyleUse a consistent style to define associations.
- FactoryBot/AttributeDefinedStaticallyAlways declare attribute values as blocks.
- FactoryBot/ConsistentParenthesesStyleUse a consistent style for parentheses in factory_bot calls.
- FactoryBot/CreateListChecks for create_list usage.
- FactoryBot/ExcessiveCreateListCheck for excessive model creation in a list.
- FactoryBot/FactoryAssociationWithStrategyUse definition in factory association instead of hard coding a strategy.
- FactoryBot/FactoryClassNameUse string value when setting the class attribute explicitly.
- FactoryBot/FactoryNameStyleChecks for name style for argument of FactoryBot::Syntax::Methods.
- FactoryBot/IdSequenceDo not create a FactoryBot sequence for an id column.
- FactoryBot/RedundantFactoryOptionChecks for redundant
factoryoption. - FactoryBot/SyntaxMethodsUse shorthands from
FactoryBot::Syntax::Methodsin your specs.
Minitest 55 rubocop-minitest 0.41.0
- Minitest/AssertEmptyThis cop enforces the test to use
assert_emptyinstead of usingassert(object.empty?). - Minitest/AssertEmptyLiteralThis cop enforces the test to use
assert_emptyinstead of usingassert_equal([], object). - Minitest/AssertEqualThis cop enforces the test to use
assert_equalinstead of usingassert(expected == actual). - Minitest/AssertInDeltaThis cop enforces the test to use
assert_in_deltainstead of usingassert_equalto compare floats. - Minitest/AssertIncludesThis cop enforces the test to use
assert_includesinstead of usingassert(collection.include?(object)). - Minitest/AssertInstanceOfThis cop enforces the test to use
assert_instance_of(Class, object)overassert(object.instance_of?(Class)) - Minitest/AssertKindOfThis cop enforces the test to use
assert_kind_of(Class, object)overassert(object.kind_of?(Class)) - Minitest/AssertMatchThis cop enforces the test to use
assert_matchinstead of usingassert(matcher.match(object)). - Minitest/AssertNilThis cop enforces the test to use
assert_nilinstead of usingassert_equal(nil, something)orassert(something.nil?). - Minitest/AssertOperatorThis cop enforces the use of
assert_operator(expected, :<, actual)overassert(expected < actual). - Minitest/AssertOutputThis cop checks for opportunities to use
assert_output. - Minitest/AssertPathExistsThis cop enforces the test to use
assert_path_existsinstead of usingassert(File.exist?(path)). - Minitest/AssertPredicateThis cop enforces the test to use
assert_predicateinstead of usingassert(obj.a_predicate_method?). - Minitest/AssertRaisesCompoundBodyThis cop enforces the block body of
assert_raises { ... }to be reduced to only the raising code. - Minitest/AssertRaisesWithRegexpArgumentThis cop enforces checks for regular expression literals passed to
assert_raises. - Minitest/AssertRespondToThis cop enforces the test to use
assert_respond_to(object, :do_something)overassert(object.respond_to?(:do_something)). - Minitest/AssertSameEnforces the use of
assert_same(expected, actual)overassert(expected.equal?(actual)). - Minitest/AssertSilentThis cop enforces the test to use
assert_silent { ... }instead of usingassert_output('', '') { ... }. - Minitest/AssertTruthyThis cop enforces the test to use
assert(actual)instead of usingassert_equal(true, actual). - Minitest/AssertWithExpectedArgumentThis cop tries to detect when a user accidentally used
assertwhen they meant to useassert_equal. - Minitest/AssertionInLifecycleHookThis cop checks for usage of assertions in lifecycle hooks.
- Minitest/DuplicateTestRunThis cop detects duplicate test runs caused by one test class inheriting from another.
- Minitest/EmptyLineBeforeAssertionMethodsAdd empty line before assertion methods.
- Minitest/FocusChecks for focused tests.
- Minitest/GlobalExpectationsThis cop checks for deprecated global expectations.
- Minitest/LifecycleHooksOrderChecks that lifecycle hooks are declared in the order in which they will be executed.
- Minitest/LiteralAsActualArgumentThis cop enforces correct order of
expectedandactualarguments forassert_equal. - Minitest/MultipleAssertionsThis cop checks if test cases contain too many assertion calls.
- Minitest/NoAssertionsThis cop checks for at least one assertion (or flunk) in tests.
- Minitest/NoTestCasesChecks if test class contains any test cases.
- Minitest/NonExecutableTestMethodChecks uses of test methods outside test class.
- Minitest/NonPublicTestMethodDetects non
public(marked asprivateorprotected) test methods. - Minitest/RedundantMessageArgumentDetects redundant message argument in assertion methods.
- Minitest/RefuteEmptyThis cop enforces to use
refute_emptyinstead of usingrefute(object.empty?). - Minitest/RefuteEqualCheck if your test uses
refute_equalinstead ofassert(expected != object)orassert(! expected == object)). - Minitest/RefuteFalseCheck if your test uses
refute(actual)instead ofassert_equal(false, actual). - Minitest/RefuteInDeltaThis cop enforces the test to use
refute_in_deltainstead of usingrefute_equalto compare floats. - Minitest/RefuteIncludesThis cop enforces the test to use
refute_includesinstead of usingrefute(collection.include?(object)). - Minitest/RefuteInstanceOfThis cop enforces the test to use
refute_instance_of(Class, object)overrefute(object.instance_of?(Class)). - Minitest/RefuteKindOfThis cop enforces the test to use
refute_kind_of(Class, object)overrefute(object.kind_of?(Class)). - Minitest/RefuteMatchThis cop enforces the test to use
refute_matchinstead of usingrefute(matcher.match(object)). - Minitest/RefuteNilThis cop enforces the test to use
refute_nilinstead of usingrefute_equal(nil, something)orrefute(something.nil?). - Minitest/RefuteOperatorThis cop enforces the use of
refute_operator(expected, :<, actual)overrefute(expected < actual). - Minitest/RefutePathExistsThis cop enforces the test to use
refute_path_existsinstead of usingrefute(File.exist?(path)). - Minitest/RefutePredicateThis cop enforces the test to use
refute_predicateinstead of usingrefute(obj.a_predicate_method?). - Minitest/RefuteRespondToThis cop enforces the test to use
refute_respond_to(object, :do_something)overrefute(object.respond_to?(:do_something)). - Minitest/RefuteSameEnforces the use of
refute_same(expected, actual)overrefute(expected.equal?(actual)). - Minitest/ReturnInTestMethodEnforces the use of
skipinstead ofreturnin test methods. - Minitest/SkipEnsureChecks that
ensurecall even ifskip. - Minitest/SkipWithoutReasonChecks for skipped tests missing the skipping reason.
- Minitest/TestFileNameChecks if test file names start with
test_or end with_test.rb. - Minitest/TestMethodNameThis cop enforces that test method names start with
test_prefix. - Minitest/UnreachableAssertionThis cop checks for an
assert_raisesblock containing any unreachable assertions. - Minitest/UnspecifiedExceptionThis cop checks for a specified error in
assert_raises. - Minitest/UselessAssertionDetects useless assertions (assertions that either always pass or always fail).
Performance 52 rubocop-performance 1.27.0
- Performance/AncestorsIncludeUse
A <= Binstead ofA.ancestors.include?(B). - Performance/ArraySemiInfiniteRangeSliceIdentifies places where slicing arrays with semi-infinite ranges can be replaced by
Array#takeandArray#drop. - Performance/BigDecimalWithNumericArgumentConvert numeric literal to string and pass it to
BigDecimal. - Performance/BindCallUse
bind_call(obj, args, ...)instead ofbind(obj).call(args, ...). - Performance/BlockGivenWithExplicitBlockCheck block argument explicitly instead of using
block_given?. - Performance/CallerUse
caller(n..n)instead ofcaller. - Performance/CaseWhenSplatReordering
whenconditions with a splat to the end of thewhenbranches can improve performance. - Performance/CasecmpUse
casecmprather thandowncase ==,upcase ==,== downcase, or== upcase.. - Performance/ChainArrayAllocationInstead of chaining array methods that allocate new arrays, mutate an existing array.
- Performance/CollectionLiteralInLoopExtract Array and Hash literals outside of loops into local variables or constants.
- Performance/CompareWithBlockUse
sort_by(&:foo)instead ofsort { |a, b| a.foo <=> b.foo }. - Performance/ConcurrentMonotonicTimeUse
Process.clock_gettime(Process::CLOCK_MONOTONIC)instead ofConcurrent.monotonic_time. - Performance/ConstantRegexpFinds regular expressions with dynamic components that are all constants.
- Performance/CountUse
countinstead of{select,find_all,filter,reject}...{size,count,length}. - Performance/DeletePrefixUse
delete_prefixinstead ofgsub. - Performance/DeleteSuffixUse
delete_suffixinstead ofgsub. - Performance/DetectUse
detectinstead ofselect.first,find_all.first,filter.first,select.last,find_all.last, andfilter.last. - Performance/DoubleStartEndWithUse
str.{start,end}_with?(x, ..., y, ...)instead ofstr.{start,end}_with?(x, ...) || str.{start,end}_with?(y, ...). - Performance/EndWithUse
end_with?instead of a regex match anchored to the end of a string. - Performance/FixedSizeDo not compute the size of statically sized objects except in constants.
- Performance/FlatMapUse
Enumerable#flat_mapinstead ofEnumerable#map...Array#flatten(1)orEnumerable#collect..Array#flatten(1). - Performance/InefficientHashSearchUse
key?orvalue?instead ofkeys.include?orvalues.include?. - Performance/IoReadlinesUse
IO.each_line(IO#each_line) instead ofIO.readlines(IO#readlines). - Performance/MapCompactUse
filter_mapinstead ofcollection.map(&:do_something).compact. - Performance/MapMethodChainChecks if the
mapmethod is used in a chain. - Performance/MethodObjectAsBlockUse block explicitly instead of block-passing a method object.
- Performance/OpenStructUse
Structinstead ofOpenStruct. - Performance/RangeIncludeUse
Range#cover?instead ofRange#include?(orRange#member?). - Performance/RedundantBlockCallUse
yieldinstead ofblock.call. - Performance/RedundantEqualityComparisonBlockChecks for uses
Enumerable#all?,Enumerable#any?,Enumerable#one?, orEnumerable#none?are compared with===or similar methods in block. - Performance/RedundantMatchUse
=~instead ofString#matchorRegexp#matchin a context where the returnedMatchDatais not needed. - Performance/RedundantMergeUse Hash#[]=, rather than Hash#merge! with a single key-value pair.
- Performance/RedundantSortBlockUse
sortinstead ofsort { |a, b| a <=> b }. - Performance/RedundantSplitRegexpArgumentIdentifies places where
splitargument can be replaced from a deterministic regexp to a string. - Performance/RedundantStringCharsChecks for redundant
String#chars. - Performance/RegexpMatchUse
match?instead ofRegexp#match,String#match,Symbol#match,Regexp#===, or=~whenMatchDatais not used. - Performance/ReverseEachUse
reverse_eachinstead ofreverse.each. - Performance/ReverseFirstUse
last(n).reverseinstead ofreverse.first(n). - Performance/SelectMapUse
filter_mapinstead ofary.select(&:foo).map(&:bar). - Performance/SizeUse
sizeinstead ofcountfor counting the number of elements inArrayandHash. - Performance/SortReverseUse
sort.reverseinstead ofsort { |a, b| b <=> a }. - Performance/SqueezeUse
squeeze('a')instead ofgsub(/a+/, 'a'). - Performance/StartWithUse
start_with?instead of a regex match anchored to the beginning of a string. - Performance/StringBytesizeUse
String#bytesizeinstead of calculating the size of the bytes array. - Performance/StringIdentifierArgumentUse symbol identifier argument instead of string identifier argument.
- Performance/StringIncludeUse
String#include?instead of a regex match with literal-only pattern. - Performance/StringReplacementUse
trinstead ofgsubwhen you are replacing the same number of characters. Usedeleteinstead ofgsubwhen you are deleting characters. - Performance/SumUse
suminstead of a custom array summation. - Performance/TimesMapChecks for .times.map calls.
- Performance/UnfreezeStringUse unary plus to get an unfrozen string literal.
- Performance/UriDefaultParserUse
URI::DEFAULT_PARSERinstead ofURI::Parser.new. - Performance/ZipWithoutBlockChecks for
map { |id| [id] }and suggests replacing it withzip.
RSpec 115 rubocop-rspec 3.10.2
- RSpec/AlignLeftLetBraceChecks that left braces for adjacent single line lets are aligned.
- RSpec/AlignRightLetBraceChecks that right braces for adjacent single line lets are aligned.
- RSpec/AnyInstanceCheck that instances are not being stubbed globally.
- RSpec/AroundBlockChecks that around blocks actually run the test.
- RSpec/BeCheck for expectations where
beis used without argument. - RSpec/BeEmptyPrefer using
be_emptywhen checking for an empty array. - RSpec/BeEqCheck for expectations where
be(...)can replaceeq(...). - RSpec/BeEqlCheck for expectations where
be(...)can replaceeql(...). - RSpec/BeNilEnsures a consistent style is used when matching
nil. - RSpec/BeforeAfterAllCheck that before/after(:all/:context) isn't being used.
- RSpec/ChangeByZeroPrefer negated matchers over
to change.by(0). - RSpec/ClassCheckEnforces consistent use of
be_aorbe_kind_of. - RSpec/ContainExactlyChecks where
contain_exactlyis used. - RSpec/ContextMethod
contextshould not be used for specifying methods. - RSpec/ContextWordingChecks that
contextdocstring starts with an allowed prefix. - RSpec/DescribeClassCheck that the first argument to the top-level describe is a constant.
- RSpec/DescribeMethodChecks that the second argument to
describespecifies a method. - RSpec/DescribeSymbolAvoid describing symbols.
- RSpec/DescribedClassChecks that tests use
described_class. - RSpec/DescribedClassModuleWrappingAvoid opening modules and defining specs within them.
- RSpec/DialectEnforces custom RSpec dialects.
- RSpec/DiscardedMatcherChecks for matchers that are used in void context.
- RSpec/DuplicatedMetadataAvoid duplicated metadata.
- RSpec/EmptyExampleGroupChecks if an example group does not include any tests.
- RSpec/EmptyHookChecks for empty before and after hooks.
- RSpec/EmptyLineAfterExampleChecks if there is an empty line after example blocks.
- RSpec/EmptyLineAfterExampleGroupChecks if there is an empty line after example group blocks.
- RSpec/EmptyLineAfterFinalLetChecks if there is an empty line after the last let block.
- RSpec/EmptyLineAfterHookChecks if there is an empty line after hook blocks.
- RSpec/EmptyLineAfterSubjectChecks if there is an empty line after subject block.
- RSpec/EmptyMetadataAvoid empty metadata hash.
- RSpec/EmptyOutputCheck that the
outputmatcher is not called with an empty string. - RSpec/EqUse
eqinstead ofbe ==to compare objects. - RSpec/ExampleLengthChecks for long examples.
- RSpec/ExampleWithoutDescriptionChecks for examples without a description.
- RSpec/ExampleWordingChecks for common mistakes in example descriptions.
- RSpec/ExcessiveDocstringSpacingChecks for excessive whitespace in example descriptions.
- RSpec/ExpectActualChecks for
expect(...)calls containing literal values. - RSpec/ExpectChangeChecks for consistent style of change matcher.
- RSpec/ExpectInHookDo not use
expectin hooks such asbefore. - RSpec/ExpectInLetDo not use
expectin let. - RSpec/ExpectOutputChecks for opportunities to use
expect { ... }.to output. - RSpec/FocusChecks if examples are focused.
- RSpec/HookArgumentChecks the arguments passed to
before,around, andafter. - RSpec/HooksBeforeExamplesChecks for before/around/after hooks that come after an example.
- RSpec/IdenticalEqualityAssertionChecks for equality assertions with identical expressions on both sides.
- RSpec/ImplicitBlockExpectationCheck that implicit block expectation syntax is not used.
- RSpec/ImplicitExpectCheck that a consistent implicit expectation style is used.
- RSpec/ImplicitSubjectChecks for usage of implicit subject (
is_expected/should). - RSpec/IncludeExamplesChecks for usage of
include_examples. - RSpec/IndexedLetDo not set up test data using indexes (e.g.,
item_1,item_2). - RSpec/InstanceSpyChecks for
instance_doubleused withhave_received. - RSpec/InstanceVariableChecks for instance variable usage in specs.
- RSpec/IsExpectedSpecifyCheck for
specifywithis_expectedand one-liner expectations. - RSpec/ItBehavesLikeChecks that only one
it_behaves_likestyle is used. - RSpec/IteratedExpectationCheck that
allmatcher is used instead of iterating over an array. - RSpec/LeadingSubjectEnforce that subject is the first definition in the test.
- RSpec/LeakyConstantDeclarationChecks that no class, module, or constant is declared.
- RSpec/LeakyLocalVariableChecks for local variables from outer scopes used inside examples.
- RSpec/LetBeforeExamplesChecks for
letdefinitions that come after an example. - RSpec/LetSetupChecks unreferenced
let!calls being used for test setup. - RSpec/MatchArrayChecks where
match_arrayis used. - RSpec/MatchWithSimpleRegexEnforces the use of
includematcher instead ofmatchwhen the matcher is a simple string literal without regex-specific features. - RSpec/MessageChainCheck that chains of messages are not being stubbed.
- RSpec/MessageExpectationChecks for consistent message expectation style.
- RSpec/MessageSpiesChecks that message expectations are set using spies.
- RSpec/MetadataStyleUse consistent metadata style.
- RSpec/MissingExampleGroupArgumentChecks that the first argument to an example group is not empty.
- RSpec/MissingExpectationTargetMethodChecks if
.to,not_toorto_notare used. - RSpec/MultipleDescribesChecks for multiple top-level example groups.
- RSpec/MultipleExpectationsChecks if examples contain too many
expectcalls. - RSpec/MultipleMemoizedHelpersChecks if example groups contain too many
letandsubjectcalls. - RSpec/MultipleSubjectsChecks if an example group defines
subjectmultiple times. - RSpec/NamedSubjectChecks for explicitly referenced test subjects.
- RSpec/NestedGroupsChecks for nested example groups.
- RSpec/NoExpectationExampleChecks if an example contains any expectation.
- RSpec/NotToNotChecks for consistent method usage for negating expectations.
- RSpec/OutputChecks for the use of output calls like puts and print in specs.
- RSpec/OverwritingSetupChecks if there is a let/subject that overwrites an existing one.
- RSpec/PendingChecks for any pending or skipped examples.
- RSpec/PendingWithoutReasonChecks for pending or skipped examples without reason.
- RSpec/PredicateMatcherPrefer using predicate matcher over using predicate method directly.
- RSpec/ReceiveCountsCheck for
onceandtwicereceive counts matchers usage. - RSpec/ReceiveMessagesPrefer
receive_messagesover multiplereceives on the same object. - RSpec/ReceiveNeverPrefer
not_to receive(...)overreceive(...).never. - RSpec/RedundantAroundRemove redundant
aroundhook. - RSpec/RedundantPredicateMatcherChecks for redundant predicate matcher.
- RSpec/RemoveConstChecks that
remove_constis not used in specs. - RSpec/RepeatedDescriptionCheck for repeated description strings in example groups.
- RSpec/RepeatedExampleCheck for repeated examples within example groups.
- RSpec/RepeatedExampleGroupBodyCheck for repeated describe and context block body.
- RSpec/RepeatedExampleGroupDescriptionCheck for repeated example group descriptions.
- RSpec/RepeatedIncludeExampleCheck for repeated include of shared examples.
- RSpec/RepeatedSubjectCallChecks for repeated calls to subject missing that it is memoized.
- RSpec/ReturnFromStubChecks for consistent style of stub's return setting.
- RSpec/ScatteredLetChecks for let scattered across the example group.
- RSpec/ScatteredSetupChecks for setup scattered across multiple hooks in an example group.
- RSpec/SharedContextChecks for proper shared_context and shared_examples usage.
- RSpec/SharedExamplesChecks for consistent style for shared example names.
- RSpec/SingleArgumentMessageChainChecks that chains of messages contain more than one element.
- RSpec/SkipBlockInsideExampleChecks for passing a block to
skipwithin examples. - RSpec/SortMetadataSort RSpec metadata alphabetically.
- RSpec/SpecFilePathFormatChecks that spec file paths are consistent and well-formed.
- RSpec/SpecFilePathSuffixChecks that spec file paths suffix are consistent and well-formed.
- RSpec/StubbedMockChecks that message expectations do not have a configured response.
- RSpec/SubjectDeclarationEnsure that subject is defined using subject helper.
- RSpec/SubjectStubChecks for stubbed test subjects.
- RSpec/UndescriptiveLiteralsDescriptionDescription should be descriptive.
- RSpec/UnspecifiedExceptionChecks for a specified error in checking raised errors.
- RSpec/VariableDefinitionChecks that memoized helpers names are symbols or strings.
- RSpec/VariableNameChecks that memoized helper names use the configured style.
- RSpec/VerifiedDoubleReferenceChecks for consistent verified double reference style.
- RSpec/VerifiedDoublesPrefer using verifying doubles over normal doubles.
- RSpec/VoidExpectChecks void
expect(). - RSpec/YieldChecks for calling a block within a stub.
RSpecRails 10 rubocop-rspec_rails 2.33.0
- RSpecRails/AvoidSetupHookChecks that tests use RSpec
beforeinstead of Railssetup. - RSpecRails/FileFixturePrefer
file_fixtureover hardcoded paths intospec/fixtures. - RSpecRails/HaveHttpStatusChecks that tests use
have_http_statusinstead of equality matchers. - RSpecRails/HttpStatusEnforces use of symbolic or numeric value to describe HTTP status.
- RSpecRails/HttpStatusNameConsistencyEnforces consistency by using the current HTTP status names.
- RSpecRails/InferredSpecTypeIdentifies redundant spec type.
- RSpecRails/MinitestAssertionsDetects Minitest-like matchers.
- RSpecRails/NegationBeValidEnforces use of
be_invalidornot_tofor negated be_valid. - RSpecRails/ReceivePerformLaterPrefer
have_enqueued_joboverreceive(:perform_later). - RSpecRails/TravelAroundChecks for time travel helpers in
aroundhooks.
Rails 138 rubocop-rails 2.38.0
- Rails/ActionControllerFlashBeforeRenderUse
flash.nowinstead offlashbeforerender. - Rails/ActionControllerTestCaseUse
ActionDispatch::IntegrationTestinstead ofActionController::TestCase. - Rails/ActionFilterEnforces consistent use of action filter methods.
- Rails/ActionOrderEnforce consistent ordering of controller actions.
- Rails/ActiveRecordAliasesAvoid Active Record aliases: Use
updateinstead ofupdate_attributes. Useupdate!instead ofupdate_attributes!. - Rails/ActiveRecordCallbacksOrderOrder callback declarations in the order in which they will be executed.
- Rails/ActiveRecordOverrideCheck for overriding Active Record methods instead of using callbacks.
- Rails/ActiveSupportAliasesAvoid ActiveSupport aliases of standard ruby methods:
String#starts_with?,String#ends_with?,Array#append,Array#prepend. - Rails/ActiveSupportOnLoadUse
ActiveSupport.on_load(...)to patch Rails framework classes. - Rails/AddColumnIndexRails migrations don't make use of a given
indexkey, but also doesn't given an error when it's used, so it makes it seem like an index might be used. - Rails/AfterCommitOverrideEnforces that there is only one call to
after_commit(and its aliases -after_create_commit,after_update_commit, andafter_destroy_commit) with the same callback name per model. - Rails/ApplicationControllerCheck that controllers subclass ApplicationController.
- Rails/ApplicationJobCheck that jobs subclass ApplicationJob.
- Rails/ApplicationMailerCheck that mailers subclass ApplicationMailer.
- Rails/ApplicationRecordCheck that models subclass ApplicationRecord.
- Rails/ArelStarEnforces
Arel.starinstead of"*"for expanded columns. - Rails/AssertNotUse
assert_notinstead ofassert !. - Rails/AttributeDefaultBlockValuePass method call in block for attribute option
default. - Rails/BelongsToUse
optional: trueinstead ofrequired: falseforbelongs_torelations. - Rails/BlankEnforces use of
blank?. - Rails/BulkChangeTableCheck whether alter queries are combinable.
- Rails/CompactBlankChecks if collection can be blank-compacted with
compact_blank. - Rails/ContentTagUse
tag.somethinginstead oftag(:something). - Rails/CreateTableWithTimestampsChecks the migration for which timestamps are not included when creating a new table.
- Rails/DangerousColumnNamesAvoid dangerous column names.
- Rails/DateChecks the correct usage of date aware methods, such as Date.today, Date.current etc.
- Rails/DefaultScopeAvoid use of
default_scope. - Rails/DelegatePrefer delegate method for delegations.
- Rails/DelegateAllowBlankDo not use allow_blank as an option to delegate.
- Rails/DeprecatedActiveModelErrorsMethodsAvoid manipulating ActiveModel errors hash directly.
- Rails/DotSeparatedKeysEnforces the use of dot-separated keys instead of
:scopeoptions inI18ntranslation methods. - Rails/DuplicateAssociationDon't repeat associations in a model.
- Rails/DuplicateScopeMultiple scopes share this same expression.
- Rails/DurationArithmeticDo not use duration as arithmetic operand with
Time.current. - Rails/DynamicFindByUse
find_byinstead of dynamicfind_by_*. - Rails/EagerEvaluationLogMessageChecks that blocks are used for interpolated strings passed to
Rails.logger.debug. - Rails/EnumHashPrefer hash syntax over array syntax when defining enums.
- Rails/EnumSyntaxUse positional arguments over keyword arguments when defining enums.
- Rails/EnumUniquenessAvoid duplicate integers in hash-syntax
enumdeclaration. - Rails/EnvUse Feature Flags or config instead of
Rails.env. - Rails/EnvLocalUse
Rails.env.local?instead ofRails.env.development? || Rails.env.test?. - Rails/EnvironmentComparisonFavor
Rails.env.production?overRails.env == 'production'. - Rails/EnvironmentVariableAccessDo not access
ENVdirectly after initialization. - Rails/ExitFavor
fail,break,return, etc. overexitin application or library code outside of Rake files to avoid exits during unit testing or running in production. - Rails/ExpandedDateRangeChecks for expanded date range.
- Rails/FilePathUse
Rails.root.joinfor file path joining. - Rails/FindByPrefer find_by over where.first.
- Rails/FindByIdFavor the use of
findoverwhere.take!,find_by!, andfind_by_id!when you need to retrieve a single record by primary key when you expect it to be found. - Rails/FindByOrAssignmentMemoizationAvoid memoizing
find_byresults with||=. - Rails/FindEachPrefer all.find_each over all.each.
- Rails/FreezeTimePrefer
freeze_timeovertravel_towith an argument of the current time. - Rails/HasAndBelongsToManyPrefer has_many :through to has_and_belongs_to_many.
- Rails/HasManyOrHasOneDependentDefine the dependent option to the has_many and has_one associations.
- Rails/HelperInstanceVariableDo not use instance variables in helpers.
- Rails/HttpPositionalArgumentsUse keyword arguments instead of positional arguments in http method calls.
- Rails/HttpStatusEnforces use of symbolic or numeric value to define HTTP status.
- Rails/HttpStatusNameConsistencyEnforces consistency by using the current HTTP status names.
- Rails/I18nLazyLookupChecks for places where I18n "lazy" lookup can be used.
- Rails/I18nLocaleAssignmentPrefer the usage of
I18n.with_localeinstead of manually updatingI18n.localevalue. - Rails/I18nLocaleTextsEnforces use of I18n and locale files instead of locale specific strings.
- Rails/IgnoredColumnsAssignmentLooks for assignments of
ignored_columnsthat override previous assignments. - Rails/IgnoredSkipActionFilterOptionChecks that
ifandonly(orexcept) are not used together as options ofskip_*action filter. - Rails/IndexByPrefer
index_byovereach_with_object,to_h, ormap. - Rails/IndexWithPrefer
index_withovereach_with_object,to_h, ormap. - Rails/InquiryPrefer Ruby's comparison operators over Active Support's
Array#inquiryandString#inquiry. - Rails/InverseOfChecks for associations where the inverse cannot be determined automatically.
- Rails/LexicallyScopedActionFilterChecks that methods specified in the filter's
onlyorexceptoptions are explicitly defined in the class. - Rails/LinkToBlankChecks that
link_towith atarget: "_blank"have arel: "noopener"option passed to them. - Rails/MailerNameMailer should end with
Mailersuffix. - Rails/MatchRouteDon't use
matchto define any routes unless there is a need to map multiple request types among [:get, :post, :patch, :put, :delete] to a single action using the:viaoption. - Rails/MigrationClassNameThe class name of the migration should match its file name.
- Rails/MultipleRoutePathsChecks for mapping a route with multiple paths, which is deprecated and will be removed in Rails 8.1.
- Rails/NegateIncludePrefer
collection.exclude?(obj)over!collection.include?(obj). - Rails/NotNullColumnDo not add a NOT NULL column without a default value to existing tables.
- Rails/OrderArgumentsPrefer symbol arguments over strings in
ordermethod. - Rails/OrderByIdDo not use the
idcolumn for ordering. Use a timestamp column to order chronologically. - Rails/OutputChecks for calls to puts, print, etc.
- Rails/OutputSafetyThe use of
html_safeorrawmay be a security risk. - Rails/PickPrefer
pickoverpluck(...).first. - Rails/PluckPrefer
pluckovermap { ... }. - Rails/PluckIdUse
idsinstead ofpluck(:id)orpluck(primary_key). - Rails/PluckInWhereUse
selectinstead ofpluckinwherequery methods. - Rails/PluralizationGrammarChecks for incorrect grammar when using methods like
3.day.ago. - Rails/PresenceChecks code that can be written more easily using
Object#presencedefined by Active Support. - Rails/PresentEnforces use of
present?. - Rails/RakeEnvironmentInclude
:environmentas a dependency for all Rake tasks. - Rails/ReadWriteAttributeChecks for read_attribute(:attr) and write_attribute(:attr, val).
- Rails/RedirectBackOrToUse
redirect_back_or_toinstead ofredirect_backwithfallback_locationoption. - Rails/RedundantActiveRecordAllMethodDetect redundant
allused as a receiver for Active Record query methods. - Rails/RedundantAllowNilFinds redundant use of
allow_nilwhenallow_blankis set to certain values in model validations. - Rails/RedundantForeignKeyChecks for associations where the
:foreign_keyoption is redundant. - Rails/RedundantPresenceValidationOnBelongsToChecks for redundant presence validation on belongs_to association.
- Rails/RedundantReceiverInWithOptionsChecks for redundant receiver in
with_options. - Rails/RedundantTravelBackChecks for redundant
travel_backcalls. - Rails/ReflectionClassNameUse a string for
class_nameoption value in the definition of a reflection. - Rails/RefuteMethodsUse
assert_notmethods instead ofrefutemethods. - Rails/RelativeDateConstantDo not assign relative date to constants.
- Rails/RenderInlinePrefer using a template over inline rendering.
- Rails/RenderPlainTextPrefer
render plain:overrender text:. - Rails/RequestRefererUse consistent syntax for request.referer.
- Rails/RequireDependencyDo not use
require_dependencywhen running in Zeitwerk mode.require_dependencyis for autoloading in classic mode. - Rails/ResponseParsedBodyPrefer
response.parsed_bodyto custom parsing logic forresponse.body. - Rails/ReversibleMigrationChecks whether the change method of the migration file is reversible.
- Rails/ReversibleMigrationMethodDefinitionChecks whether the migration implements either a
changemethod or both anupand adownmethod. - Rails/RootJoinChainUse a single
#joininstead of chaining onRails.rootorRails.public_path. - Rails/RootPathnameMethodsUse
Rails.rootIO methods instead of passing it toFile. - Rails/RootPublicPathFavor
Rails.public_pathoverRails.rootwith'public'. - Rails/SafeNavigationUse Ruby's safe navigation operator (
&.) instead oftry!. - Rails/SafeNavigationWithBlankAvoid
foo&.blank?in conditionals. - Rails/SaveBangIdentifies possible cases where Active Record save! or related should be used.
- Rails/SchemaCommentEnforces the use of the
commentoption when adding a new table or column to the database during a migration. - Rails/ScopeArgsChecks the arguments of ActiveRecord scopes.
- Rails/SelectMapChecks for uses of
select(:column_name)withmap(&:column_name). - Rails/ShortI18nUse the short form of the I18n methods:
tinstead oftranslateandlinstead oflocalize. - Rails/SkipsModelValidationsUse methods that skips model validations with caution. See reference for more information.
- Rails/SquishedSQLHeredocsChecks SQL heredocs to use
.squish. - Rails/StripHeredocEnforces the use of squiggly heredoc over
strip_heredoc. - Rails/StrongParametersExpectEnforces the use of
ActionController::Parameters#expectas a method for strong parameter handling. - Rails/TableNameAssignmentDo not use
self.table_name =. Use Inflections ortable_name_prefixinstead. - Rails/ThreeStateBooleanColumnAdd a default value and a
NOT NULLconstraint to boolean columns. - Rails/TimeZoneChecks the correct usage of time zone aware methods.
- Rails/TimeZoneAssignmentPrefer the usage of
Time.use_zoneinstead of manually updatingTime.zonevalue. - Rails/ToFormattedSChecks for consistent uses of
to_fsorto_formatted_s. - Rails/ToSWithArgumentIdentifies passing any argument to
#to_s. - Rails/TopLevelHashWithIndifferentAccessIdentifies top-level
HashWithIndifferentAccess. - Rails/TransactionExitStatementAvoid the usage of
return,breakandthrowin transaction blocks. - Rails/UniqBeforePluckPrefer the use of uniq or distinct before pluck.
- Rails/UniqueValidationWithoutIndexUniqueness validation should have a unique index on the database column.
- Rails/UnknownEnvUse correct environment name.
- Rails/UnusedIgnoredColumnsRemove a column that does not exist from
ignored_columns. - Rails/UnusedRenderContentDo not specify body content for a response with a non-content status code.
- Rails/ValidationUse validates :attribute, hash of validations.
- Rails/WhereEqualsPass conditions to
whereandwhere.notas a hash instead of manually constructing SQL. - Rails/WhereExistsPrefer
exists?(...)overwhere(...).exists?. - Rails/WhereMissingUse
where.missing(...)to find missing relationship records. - Rails/WhereNotUse
where.not(...)instead of manually constructing negated SQL inwhere. - Rails/WhereNotWithMultipleConditionsDo not use
where.not(...)with multiple conditions. - Rails/WhereRangeUse ranges in
whereinstead of manually constructing SQL.
ThreadSafety 10 rubocop-thread_safety 0.8.0
- ThreadSafety/ActiveSupportCallbacksAvoid mutating ActiveSupport callback chains at runtime.
- ThreadSafety/ClassAndModuleAttributesAvoid mutating class and module attributes.
- ThreadSafety/ClassInstanceVariableAvoid class instance variables.
- ThreadSafety/DirChdirAvoid using
Dir.chdirdue to its process-wide effect. - ThreadSafety/EnvMutationAvoid mutating
ENVdue to its process-wide effect. - ThreadSafety/LazySynchronizationPrimitiveDo not lazily initialize synchronization primitives with
||=. - ThreadSafety/MethodRedefinitionDo not use
remove_methodfollowed by method definition. - ThreadSafety/MutableClassInstanceVariableDo not assign mutable objects to class instance variables.
- ThreadSafety/NewThreadAvoid starting new threads. Let a framework like Sidekiq handle the threads.
- ThreadSafety/RackMiddlewareInstanceVariableAvoid instance variables in Rack middleware.
No cops match. Try fewer filters, or * as a wildcard.
on by default
pending: off until the next major release, or with NewCops: enable
opt-in: off unless enabled
-a fixed by rubocop -a
-A only by rubocop -A
numbers: the version that added it