repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/capture.rb | sinatra-contrib/lib/sinatra/capture.rb | require 'sinatra/base'
require 'sinatra/engine_tracking'
module Sinatra
#
# = Sinatra::Capture
#
# Extension that enables blocks inside other extensions.
# It currently works for erb, slim and haml.
# Enables mixing of different template languages.
#
# Example:
#
# # in hello_world.erb
#
# Say
# <% a = capture do %>World<% end %>
# Hello <%= a %>!
#
# # in hello_world.slim
#
# | Say
# - a = capture do
# | World
# | Hello #{a}!
#
# # in hello_world.haml
#
# Say
# - a = capture do
# World
# Hello #{a.strip}!
#
#
# You can also use nested blocks.
#
# Example
#
# # in hello_world.erb
#
# Say
# <% a = capture do %>
# <% b = capture do %>World<% end %>
# <%= b %>!
# <% end %>
# Hello <%= a.strip %>
#
#
# The main advantage of capture is mixing of different template engines.
#
# Example
#
# # in mix_me_up.slim
#
# - two = capture do
# - erb "<%= 1 + 1 %>"
# | 1 + 1 = #{two}
#
# == Usage
#
# === Classic Application
#
# In a classic application simply require the helpers, and start using them:
#
# require "sinatra"
# require "sinatra/capture"
#
# # The rest of your classic application code goes here...
#
# === Modular Application
#
# In a modular application you need to require the helpers, and then tell
# the application you will use them:
#
# require "sinatra/base"
# require "sinatra/capture"
#
# class MyApp < Sinatra::Base
# helpers Sinatra::Capture
#
# # The rest of your modular application code goes here...
# end
#
module Capture
include Sinatra::EngineTracking
def capture(*args, &block)
return block[*args] if ruby?
if haml? && Tilt[:haml] == Tilt::HamlTemplate && defined?(Haml::Buffer)
buffer = Haml::Buffer.new(nil, Haml::Options.new.for_buffer)
with_haml_buffer(buffer) { capture_haml(*args, &block) }
else
buf_was = @_out_buf
@_out_buf = +''
begin
raw = block[*args]
captured = block.binding.eval('@_out_buf')
captured.empty? ? raw : captured
ensure
@_out_buf = buf_was
end
end
end
def capture_later(&block)
engine = current_engine
proc { |*a| with_engine(engine) { @capture = capture(*a, &block) } }
end
end
helpers Capture
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/config_file.rb | sinatra-contrib/lib/sinatra/config_file.rb | require 'sinatra/base'
require 'yaml'
require 'erb'
module Sinatra
# = Sinatra::ConfigFile
#
# <tt>Sinatra::ConfigFile</tt> is an extension that allows you to load the
# application's configuration from YAML files. It automatically detects if
# the files contain specific environment settings and it will use those
# corresponding to the current one.
#
# You can access those options through +settings+ within the application. If
# you try to get the value for a setting that hasn't been defined in the
# config file for the current environment, you will get whatever it was set
# to in the application.
#
# == Usage
#
# Once you have written your configurations to a YAML file you can tell the
# extension to load them. See below for more information about how these
# files are interpreted.
#
# For the examples, lets assume the following config.yml file:
#
# greeting: Welcome to my file configurable application
#
# === Classic Application
#
# require "sinatra"
# require "sinatra/config_file"
#
# config_file 'path/to/config.yml'
#
# get '/' do
# @greeting = settings.greeting
# haml :index
# end
#
# # The rest of your classic application code goes here...
#
# === Modular Application
#
# require "sinatra/base"
# require "sinatra/config_file"
#
# class MyApp < Sinatra::Base
# register Sinatra::ConfigFile
#
# config_file 'path/to/config.yml'
#
# get '/' do
# @greeting = settings.greeting
# haml :index
# end
#
# # The rest of your modular application code goes here...
# end
#
# === Config File Format
#
# In its most simple form this file is just a key-value list:
#
# foo: bar
# something: 42
# nested:
# a: 1
# b: 2
#
# But it also can provide specific environment configuration. There are two
# ways to do that: at the file level and at the settings level.
#
# At the settings level (e.g. in 'path/to/config.yml'):
#
# development:
# foo: development
# bar: bar
# test:
# foo: test
# bar: bar
# production:
# foo: production
# bar: bar
#
# Or at the file level:
#
# foo:
# development: development
# test: test
# production: production
# bar: bar
#
# In either case, <tt>settings.foo</tt> will return the environment name, and
# <tt>settings.bar</tt> will return <tt>"bar"</tt>.
#
# If you wish to provide defaults that may be shared among all the
# environments, this can be done by using a YAML alias, and then overwriting
# values in environments where appropriate:
#
# default: &common_settings
# foo: 'foo'
# bar: 'bar'
#
# production:
# <<: *common_settings
# bar: 'baz' # override the default value
#
module ConfigFile
# When the extension is registered sets the +environments+ setting to the
# traditional environments: development, test and production.
def self.registered(base)
base.set :environments, %w[test production development]
end
# Loads the configuration from the YAML files whose +paths+ are passed as
# arguments, filtering the settings for the current environment. Note that
# these +paths+ can actually be globs.
def config_file(*paths)
Dir.chdir(root || '.') do
paths.each do |pattern|
Dir.glob(pattern) do |file|
raise UnsupportedConfigType unless ['.yml', '.yaml', '.erb'].include?(File.extname(file))
logger.info "loading config file '#{file}'" if logging? && respond_to?(:logger)
document = ERB.new(File.read(file)).result
yaml = YAML.respond_to?(:unsafe_load) ? YAML.unsafe_load(document) : YAML.load(document)
config = config_for_env(yaml)
config.each_pair { |key, value| set(key, value) }
end
end
end
end
class UnsupportedConfigType < StandardError
def message
'Invalid config file type, use .yml, .yaml or .erb'
end
end
private
# Given a +hash+ containing application configuration it returns
# settings applicable to the current environment. Note: It gives
# precedence to environment settings defined at the root-level.
def config_for_env(hash)
return from_environment_key(hash) if environment_keys?(hash)
hash.each_with_object(IndifferentHash[]) do |(k, v), acc|
if environment_keys?(v)
acc.merge!(k => v[environment.to_s]) if v.key?(environment.to_s)
else
acc.merge!(k => v)
end
end
end
# Given a +hash+ returns the settings corresponding to the current
# environment.
def from_environment_key(hash)
hash[environment.to_s] || hash[environment.to_sym] || {}
end
# Returns true if supplied with a hash that has any recognized
# +environments+ in its root keys.
def environment_keys?(hash)
hash.is_a?(Hash) && hash.any? { |k, _| environments.include?(k.to_s) }
end
end
register ConfigFile
Delegator.delegate :config_file
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/namespace.rb | sinatra-contrib/lib/sinatra/namespace.rb | # frozen_string_literal: true
require 'sinatra/base'
require 'mustermann'
module Sinatra
# = Sinatra::Namespace
#
# <tt>Sinatra::Namespace</tt> is an extension that adds namespaces to an
# application. This namespaces will allow you to share a path prefix for the
# routes within the namespace, and define filters, conditions and error
# handlers exclusively for them. Besides that, you can also register helpers
# and extensions that will be used only within the namespace.
#
# == Usage
#
# Once you have loaded the extension (see below), you can use the +namespace+
# method to define namespaces in your application.
#
# You can define a namespace by a path prefix:
#
# namespace '/blog' do
# get { haml :blog }
# get '/:entry_permalink' do
# @entry = Entry.find_by_permalink!(params[:entry_permalink])
# haml :entry
# end
#
# # More blog routes...
# end
#
# by a condition:
#
# namespace :host_name => 'localhost' do
# get('/admin/dashboard') { haml :dashboard }
# get('/admin/login') { haml :login }
#
# # More admin routes...
# end
#
# or both:
#
# namespace '/admin', :host_name => 'localhost' do
# get('/dashboard') { haml :dashboard }
# get('/login') { haml :login }
# post('/login') { login_user }
#
# # More admin routes...
# end
#
# Regex is also accepted:
#
# namespace /\/posts\/([^\/&?]+)\// do
# get { haml :blog }
#
# # More blog routes...
# end
#
# When you define a filter or an error handler, or register an extension or a
# set of helpers within a namespace, they only affect the routes defined in
# it. For instance, lets define a before filter to prevent the access of
# unauthorized users to the admin section of the application:
#
# namespace '/admin' do
# helpers AdminHelpers
# before { authenticate unless request.path_info == '/admin/login' }
#
# get '/dashboard' do
# # Only authenticated users can access here...
# haml :dashboard
# end
#
# # More admin routes...
# end
#
# get '/' do
# # Any user can access here...
# haml :index
# end
#
# Well, they actually also affect the nested namespaces:
#
# namespace '/admin' do
# helpers AdminHelpers
# before { authenticate unless request.path_info == '/admin/login' }
#
# namespace '/users' do
# get do
# # Only authenticated users can access here...
# @users = User.all
# haml :users
# end
#
# # More user admin routes...
# end
#
# # More admin routes...
# end
#
# Redirecting within the namespace can be done using redirect_to:
#
# namespace '/admin' do
# get '/foo' do
# redirect_to '/bar' # Redirects to /admin/bar
# end
#
# get '/foo' do
# redirect '/bar' # Redirects to /bar
# end
# end
#
# === Classic Application Setup
#
# To be able to use namespaces in a classic application all you need to do is
# require the extension:
#
# require "sinatra"
# require "sinatra/namespace"
#
# namespace '/users' do
# end
#
# === Modular Application Setup
#
# To be able to use namespaces in a modular application all you need to do is
# require the extension, and then, register it:
#
# require "sinatra/base"
# require "sinatra/namespace"
#
# class MyApp < Sinatra::Base
# register Sinatra::Namespace
#
# namespace '/users' do
# end
# end
#
# === Within an extension
#
# To be able to use namespaces within an extension, you need to first create
# an extension. This includes defining the `registered(app)` method in the
# module.
#
# require 'sinatra/base' # For creating Sinatra extensions
# require 'sinatra/namespace' # To create namespaces
#
# module Zomg # Keep everything under "Zomg" namespace for sanity
# module Routes # Define a new "Routes" module
#
# def self.registered(app)
# # First, register the Namespace extension
# app.register Sinatra::Namespace
#
# # This defines an `/api` namespace on the application
# app.namespace '/api' do
# get '/users' do
# # do something with `GET "/api/users"`
# end
# end
#
# end
# end
#
# # Lastly, register the extension to use in our app
# Sinatra.register Routes
# end
#
# In order to use this extension, is the same as any other Sinatra extension:
#
# module Zomg
# # Define our app class, we use modular app for this example
# class App < Sinatra::Base
# # this gives us all the namespaces we defined earlier
# register Routes
#
# get '/' do
# "Welcome to my application!"
# end
# end
# end
#
# Zomg::App.run! # Don't forget to start your app ;)
#
# Phew! That was a mouthful.
#
# I hope that helps you use `Sinatra::Namespace` in every way imaginable!
#
module Namespace
def self.new(base, pattern, conditions = {}, &block)
Module.new do
# quelch uninitialized variable warnings, since these get used by compile method.
@pattern = nil
@conditions = nil
extend NamespacedMethods
include InstanceMethods
@base = base
@extensions = []
@errors = {}
@pattern, @conditions = compile(pattern, conditions)
@templates = Hash.new { |_h, k| @base.templates[k] }
namespace = self
before { extend(@namespace = namespace) }
class_eval(&block)
end
end
module InstanceMethods
def settings
@namespace
end
def template_cache
super.fetch(:nested, @namespace) { TemplateCache.new }
end
def redirect_to(uri, *args)
redirect("#{@namespace.pattern}#{uri}", *args)
end
end
module SharedMethods
def namespace(pattern, conditions = {}, &block)
Sinatra::Namespace.new(self, pattern, conditions, &block)
end
end
module NamespacedMethods
include SharedMethods
attr_reader :base, :templates
ALLOWED_ENGINES = %i[
erb erubi haml hamlit builder nokogiri sass scss
liquid markdown rdoc asciidoc markaby
rabl slim yajl
]
def self.prefixed(*names)
names.each { |n| define_method(n) { |*a, &b| prefixed(n, *a, &b) } }
end
prefixed :before, :after, :delete, :get, :head, :options, :patch, :post, :put
def helpers(*extensions, &block)
class_eval(&block) if block_given?
include(*extensions) if extensions.any?
end
def register(*extensions, &block)
extensions << Module.new(&block) if block_given?
@extensions += extensions
extensions.each do |extension|
extend extension
extension.registered(self) if extension.respond_to?(:registered)
end
end
def invoke_hook(name, *args)
@extensions.each { |e| e.send(name, *args) if e.respond_to?(name) }
end
def not_found(&block)
error(Sinatra::NotFound, &block)
end
def errors
base.errors.merge(namespace_errors)
end
def namespace_errors
@errors
end
def error(*codes, &block)
args = Sinatra::Base.send(:compile!, 'ERROR', /.*/, block)
codes = codes.map { |c| Array(c) }.flatten
codes << Exception if codes.empty?
codes << Sinatra::NotFound if codes.include?(404)
codes.each do |c|
errors = @errors[c] ||= []
errors << args
end
end
def respond_to(*args)
return @conditions[:provides] || base.respond_to if args.empty?
@conditions[:provides] = args
end
def set(key, value = self, &block)
return key.each { |k, v| set(k, v) } if key.respond_to?(:each) && block.nil? && (value == self)
raise ArgumentError, "may not set #{key}" unless ([:views] + ALLOWED_ENGINES).include?(key)
block ||= proc { value }
singleton_class.send(:define_method, key, &block)
end
def enable(*opts)
opts.each { |key| set(key, true) }
end
def disable(*opts)
opts.each { |key| set(key, false) }
end
def template(name, &block)
first_location = caller_locations.first
filename = first_location.path
line = first_location.lineno
templates[name] = [block, filename, line]
end
def layout(name = :layout, &block)
template name, &block
end
def pattern
@pattern
end
private
def app
base.respond_to?(:base) ? base.base : base
end
def compile(pattern, conditions, default_pattern = nil)
if pattern.respond_to? :to_hash
conditions = conditions.merge pattern.to_hash
pattern = nil
end
base_pattern = @pattern
base_conditions = @conditions
pattern ||= default_pattern
[prefixed_path(base_pattern, pattern),
(base_conditions || {}).merge(conditions)]
end
def prefixed_path(a, b)
return a || b || /.*/ unless a && b
return Mustermann.new(b) if a == /.*/
Mustermann.new(a) + Mustermann.new(b)
end
def prefixed(method, pattern = nil, conditions = {}, &block)
default = %r{(?:/.*)?} if (method == :before) || (method == :after)
pattern, conditions = compile pattern, conditions, default
result = base.send(method, pattern, **conditions, &block)
invoke_hook :route_added, method.to_s.upcase, pattern, block
result
end
def method_missing(method, *args, &block)
base.send(method, *args, &block)
end
def respond_to?(method, include_private = false)
super || base.respond_to?(method, include_private)
end
end
module BaseMethods
include SharedMethods
end
def self.extended(base)
base.extend BaseMethods
end
end
register Sinatra::Namespace
Delegator.delegate :namespace
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/contrib.rb | sinatra-contrib/lib/sinatra/contrib.rb | # frozen_string_literal: true
require 'sinatra/contrib/setup'
module Sinatra
module Contrib
##
# Common middleware that doesn't bring run time overhead if not used
# or breaks if external dependencies are missing. Will extend
# Sinatra::Application by default.
module Common
register :ConfigFile, 'sinatra/config_file'
register :MultiRoute, 'sinatra/multi_route'
register :Namespace, 'sinatra/namespace'
register :RespondWith, 'sinatra/respond_with'
helpers :Capture, 'sinatra/capture'
helpers :ContentFor, 'sinatra/content_for'
helpers :Cookies, 'sinatra/cookies'
helpers :EngineTracking, 'sinatra/engine_tracking'
helpers :JSON, 'sinatra/json'
helpers :LinkHeader, 'sinatra/link_header'
helpers :Streaming, 'sinatra/streaming'
helpers :RequiredParams, 'sinatra/required_params'
end
##
# Other extensions you don't want to be loaded unless needed.
module Custom
register :Reloader, 'sinatra/reloader'
helpers :HamlHelpers, 'sinatra/haml_helpers'
end
##
# Stuff that aren't Sinatra extensions, technically.
autoload :Extension, 'sinatra/extension'
autoload :TestHelpers, 'sinatra/test_helpers'
end
register Sinatra::Contrib::Common
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/json.rb | sinatra-contrib/lib/sinatra/json.rb | # frozen_string_literal: true
require 'sinatra/base'
require 'multi_json'
module Sinatra
# = Sinatra::JSON
#
# <tt>Sinatra::JSON</tt> adds a helper method, called +json+, for (obviously)
# json generation.
#
# == Usage
#
# === Classic Application
#
# In a classic application simply require the helper, and start using it:
#
# require "sinatra"
# require "sinatra/json"
#
# # define a route that uses the helper
# get '/' do
# json :foo => 'bar'
# end
#
# # The rest of your classic application code goes here...
#
# === Modular Application
#
# In a modular application you need to require the helper, and then tell the
# application you will use it:
#
# require "sinatra/base"
# require "sinatra/json"
#
# class MyApp < Sinatra::Base
#
# # define a route that uses the helper
# get '/' do
# json :foo => 'bar'
# end
#
# # The rest of your modular application code goes here...
# end
#
# === Encoders
#
# By default it will try to call +to_json+ on the object, but if it doesn't
# respond to that message, it will use its own rather simple encoder. You can
# easily change that anyways. To use +JSON+, simply require it:
#
# require 'json'
#
# The same goes for <tt>Yajl::Encoder</tt>:
#
# require 'yajl'
#
# For other encoders, besides requiring them, you need to define the
# <tt>:json_encoder</tt> setting. For instance, for the +Whatever+ encoder:
#
# require 'whatever'
# set :json_encoder, Whatever
#
# To force +json+ to simply call +to_json+ on the object:
#
# set :json_encoder, :to_json
#
# Actually, it can call any method:
#
# set :json_encoder, :my_fancy_json_method
#
# === Content-Type
#
# It will automatically set the content type to "application/json". As
# usual, you can easily change that, with the <tt>:json_content_type</tt>
# setting:
#
# set :json_content_type, :js
#
# === Overriding the Encoder and the Content-Type
#
# The +json+ helper will also take two options <tt>:encoder</tt> and
# <tt>:content_type</tt>. The values of this options are the same as the
# <tt>:json_encoder</tt> and <tt>:json_content_type</tt> settings,
# respectively. You can also pass those to the json method:
#
# get '/' do
# json({:foo => 'bar'}, :encoder => :to_json, :content_type => :js)
# end
#
module JSON
class << self
def encode(object)
::MultiJson.dump(object)
end
end
def json(object, options = {})
content_type resolve_content_type(options)
resolve_encoder_action object, resolve_encoder(options)
end
private
def resolve_content_type(options = {})
options[:content_type] || settings.json_content_type
end
def resolve_encoder(options = {})
options[:json_encoder] || settings.json_encoder
end
def resolve_encoder_action(object, encoder)
%i[encode generate].each do |method|
return encoder.send(method, object) if encoder.respond_to? method
end
raise "#{encoder} does not respond to #generate nor #encode" unless encoder.is_a? Symbol
object.__send__(encoder)
end
end
Base.set :json_encoder do
::MultiJson
end
Base.set :json_content_type, :json
# Load the JSON helpers in modular style automatically
Base.helpers JSON
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/haml_helpers.rb | sinatra-contrib/lib/sinatra/haml_helpers.rb | # frozen_string_literal: true
require 'sinatra/base'
require 'sinatra/capture'
module Sinatra
# = Sinatra::HamlHelpers
#
# This extension provides some of the helper methods that existed in Haml 5
# but were removed in Haml 6. To use this in your app, just +register+ it:
#
# require 'sinatra/base'
# require 'sinatra/haml_helpers'
#
# class Application < Sinatra::Base
# helpers Sinatra::HamlHelpers
#
# # now you can use the helpers in your views
# get '/' do
# haml_code = <<~HAML
# %p
# != surround "(", ")" do
# %a{ href: "https://example.org/" } example.org
# HAML
# haml haml_code
# end
# end
#
module HamlHelpers
include Sinatra::Capture
def surround(front, back = front, &block)
"#{front}#{_capture_haml(&block).chomp}#{back}\n"
end
def precede(str, &block)
"#{str}#{_capture_haml(&block).chomp}\n"
end
def succeed(str, &block)
"#{_capture_haml(&block).chomp}#{str}\n"
end
def _capture_haml(*args, &block)
capture(*args, &block)
end
end
helpers HamlHelpers
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/runner.rb | sinatra-contrib/lib/sinatra/runner.rb | # frozen_string_literal: true
require 'open-uri'
require 'net/http'
require 'timeout'
module Sinatra
# NOTE: This feature is experimental, and missing tests!
#
# Helps you spinning up and shutting down your own sinatra app. This is especially helpful for running
# real network tests against a sinatra backend.
#
# The backend server could look like the following (in test/server.rb).
#
# require "sinatra"
#
# get "/" do
# "Cheers from test server"
# end
#
# get "/ping" do
# "1"
# end
#
# Note that you need to implement a ping action for internal use.
#
# Next, you need to write your runner.
#
# require 'sinatra/runner'
#
# class Runner < Sinatra::Runner
# def app_file
# File.expand_path("server.rb", __dir__)
# end
# end
#
# Override Runner#app_file, #command, #port, #protocol and #ping_path for customization.
#
# **Don't forget to override #app_file specific to your application!**
#
# Wherever you need this test backend, here's how you manage it. The following example assumes you
# have a test in your app that needs to be run against your test backend.
#
# runner = ServerRunner.new
# runner.run
#
# # ..tests against localhost:4567 here..
#
# runner.kill
#
# For an example, check https://github.com/apotonick/roar/blob/master/test/integration/runner.rb
class Runner
def app_file
File.expand_path('server.rb', __dir__)
end
def run
@pipe = start
@started = Time.now
warn "#{server} up and running on port #{port}" if ping
end
def kill
return unless pipe
Process.kill('KILL', pipe.pid)
rescue NotImplementedError
system "kill -9 #{pipe.pid}"
rescue Errno::ESRCH
end
def get(url)
Timeout.timeout(1) { get_url("#{protocol}://127.0.0.1:#{port}#{url}") }
end
def get_stream(url = '/stream', &block)
Net::HTTP.start '127.0.0.1', port do |http|
request = Net::HTTP::Get.new url
http.request request do |response|
response.read_body(&block)
end
end
end
def get_response(url)
Net::HTTP.start '127.0.0.1', port do |http|
request = Net::HTTP::Get.new url
http.request request do |response|
response
end
end
end
def log
@log ||= +''
loop { @log << pipe.read_nonblock(1) }
rescue Exception
@log
end
private
attr_accessor :pipe
def start
IO.popen(command)
end
# to be overwritten
def command
"bundle exec ruby #{app_file} -p #{port} -e production"
end
def ping(timeout = 30)
loop do
return if alive?
if Time.now - @started > timeout
warn command, log
raise "timeout starting server with command '#{command}'"
else
sleep 0.1
end
end
end
def alive?
3.times { get(ping_path) }
true
rescue EOFError, SystemCallError, OpenURI::HTTPError, Timeout::Error
false
end
# to be overwritten
def ping_path
'/ping'
end
# to be overwritten
def port
4567
end
def protocol
'http'
end
def get_url(url)
uri = URI.parse(url)
return uri.read unless protocol == 'https'
get_https_url(uri)
end
def get_https_url(uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
http.request(request).body
end
end
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/multi_route.rb | sinatra-contrib/lib/sinatra/multi_route.rb | # frozen_string_literal: true
require 'sinatra/base'
module Sinatra
# = Sinatra::MultiRoute
#
# Create multiple routes with one statement.
#
# == Usage
#
# Use this extension to create a handler for multiple routes:
#
# get '/foo', '/bar' do
# # ...
# end
#
# Or for multiple verbs:
#
# route :get, :post, '/' do
# # ...
# end
#
# Or for multiple verbs and multiple routes:
#
# route :get, :post, ['/foo', '/bar'] do
# # ...
# end
#
# Or even for custom verbs:
#
# route 'LIST', '/' do
# # ...
# end
#
# === Classic Application
#
# To use the extension in a classic application all you need to do is require
# it:
#
# require "sinatra"
# require "sinatra/multi_route"
#
# # Your classic application code goes here...
#
# === Modular Application
#
# To use the extension in a modular application you need to require it, and
# then, tell the application you will use it:
#
# require "sinatra/base"
# require "sinatra/multi_route"
#
# class MyApp < Sinatra::Base
# register Sinatra::MultiRoute
#
# # The rest of your modular application code goes here...
# end
#
module MultiRoute
def head(*args, &block) super(*route_args(args), &block) end
def delete(*args, &block) super(*route_args(args), &block) end
def get(*args, &block) super(*route_args(args), &block) end
def options(*args, &block) super(*route_args(args), &block) end
def patch(*args, &block) super(*route_args(args), &block) end
def post(*args, &block) super(*route_args(args), &block) end
def put(*args, &block) super(*route_args(args), &block) end
def route(*args, &block)
options = Hash === args.last ? args.pop : {}
routes = [*args.pop]
args.each do |verb|
verb = verb.to_s.upcase if Symbol === verb
routes.each do |route|
super(verb, route, options, &block)
end
end
end
private
def route_args(args)
options = Hash === args.last ? args.pop : {}
[args, options]
end
end
register MultiRoute
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/test_helpers.rb | sinatra-contrib/lib/sinatra/test_helpers.rb | # frozen_string_literal: true
require 'sinatra/base'
require 'rack'
begin
require 'rack/test'
rescue LoadError
abort 'Add rack-test to your Gemfile to use this module!'
end
require 'forwardable'
module Sinatra
Base.set :environment, :test
# Helper methods to ease testing your Sinatra application. Partly extracted
# from Sinatra. Testing framework agnostic.
module TestHelpers
include Rack::Test::Methods
extend Forwardable
attr_accessor :settings
# @!group Instance Methods delegated to last_response
# @!method body
#
# Body of last_response
#
# @see https://www.rubydoc.info/github/rack/rack/main/Rack/Response#body-instance_method
# @return [String] body of the last response
# @!method headers
#
# Headers of last_response
#
# @return [Hash] hash of the last response
# @!method status
#
# HTTP status of last_response
#
# @return [Integer] HTTP status of the last response
# @!method errors
#
# Errors of last_response
#
# @return [Array] errors of the last response
def_delegators :last_response, :body, :headers, :status, :errors
# @!endgroup
# @!group Class Methods delegated to app
# @!method configure(*envs) {|_self| ... }
# @!scope class
# @yieldparam _self [Sinatra::Base] the object that the method was called on
#
# Set configuration options for Sinatra and/or the app. Allows scoping of
# settings for certain environments.
# @!method set(option, value = (not_set = true), ignore_setter = false, &block)
# @!scope class
# Sets an option to the given value. If the value is a proc, the proc will
# be called every time the option is accessed.
# @raise [ArgumentError]
# @!method enable(*opts)
# @!scope class
#
# Same as calling `set :option, true` for each of the given options.
# @!method disable(*opts)
# @!scope class
#
# Same as calling `set :option, false` for each of the given options.
# @!method use(middleware, *args, &block)
# @!scope class
# Use the specified Rack middleware
# @!method helpers(*extensions, &block)
# @!scope class
#
# Makes the methods defined in the block and in the Modules given in
# `extensions` available to the handlers and templates.
# @!method register(*extensions, &block)
# @!scope class
# Register an extension. Alternatively take a block from which an
# extension will be created and registered on the fly.
def_delegators :app, :configure, :set, :enable, :disable, :use, :helpers, :register
# @!endgroup
# @!group Instance Methods delegated to current_session
# @!method env_for(uri = "", opts = {})
#
# Return the Rack environment used for a request to `uri`.
#
# @return [Hash]
def_delegators :current_session, :env_for
# @!endgroup
# @!group Instance Methods delegated to rack_mock_session
# @!method cookie_jar
#
# Returns a {https://www.rubydoc.info/github/rack/rack-test/Rack/Test/CookieJar Rack::Test::CookieJar}.
#
# @return [Rack::Test::CookieJar]
def_delegators :rack_mock_session, :cookie_jar
# @!endgroup
# Instantiate and configure a mock Sinatra app.
#
# Takes a `base` app class, or defaults to Sinatra::Base, and instantiates
# an app instance. Any given code in `block` is `class_eval`'d on this new
# instance before the instance is returned.
#
# @param base [Sinatra::Base] App base class
#
# @return [Sinatra] Configured mocked app
def mock_app(base = Sinatra::Base, &block)
inner = nil
@app = Sinatra.new(base) do
inner = self
class_eval(&block)
end
@settings = inner
app
end
# Replaces the configured app.
#
# @param base [Sinatra::Base] a configured app
def app=(base)
@app = base
end
alias set_app app=
# Returns a Rack::Lint-wrapped Sinatra app.
#
# If no app has been configured, a new subclass of Sinatra::Base will be
# used and stored.
#
# (Rack::Lint validates your application and the requests and
# responses according to the Rack spec.)
#
# @return [Sinatra::Base]
def app
@app ||= Class.new Sinatra::Base
Rack::Lint.new @app
end
unless method_defined? :options
# Processes an OPTIONS request in the context of the current session.
#
# @param uri [String]
# @param params [Hash]
# @param env [Hash]
def options(uri, params = {}, env = {}, &block)
env = env_for(uri, env.merge(method: 'OPTIONS', params: params))
current_session.send(:process_request, uri, env, &block)
end
end
unless method_defined? :patch
# Processes a PATCH request in the context of the current session.
#
# @param uri [String]
# @param params [Hash]
# @param env [Hash]
def patch(uri, params = {}, env = {}, &block)
env = env_for(uri, env.merge(method: 'PATCH', params: params))
current_session.send(:process_request, uri, env, &block)
end
end
# @return [Boolean]
def last_request?
last_request
true
rescue Rack::Test::Error
false
end
# @raise [Rack::Test:Error] If sessions are not enabled for app
# @return [Hash] Session of last request, or the empty Hash
def session
return {} unless last_request?
raise Rack::Test::Error, 'session not enabled for app' unless last_env['rack.session'] || app.session?
last_request.session
end
# @return The env of the last request
def last_env
last_request.env
end
end
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/streaming.rb | sinatra-contrib/lib/sinatra/streaming.rb | # frozen_string_literal: true
require 'sinatra/base'
module Sinatra
# = Sinatra::Streaming
#
# Sinatra 1.3 introduced the +stream+ helper. This addon improves the
# streaming API by making the stream object imitate an IO object, turning
# it into a real Deferrable and making the body play nicer with middleware
# unaware of streaming.
#
# == IO-like behavior
#
# This is useful when passing the stream object to a library expecting an
# IO or StringIO object.
#
# get '/' do
# stream do |out|
# out.puts "Hello World!", "How are you?"
# out.write "Written #{out.pos} bytes so far!\n"
# out.putc(65) unless out.closed?
# out.flush
# end
# end
#
# == Better Middleware Handling
#
# Blocks passed to #map! or #map will actually be applied when streaming
# takes place (as you might have suspected, #map! applies modifications
# to the current body, while #map creates a new one):
#
# class StupidMiddleware
# def initialize(app) @app = app end
#
# def call(env)
# status, headers, body = @app.call(env)
# body.map! { |e| e.upcase }
# [status, headers, body]
# end
# end
#
# use StupidMiddleware
#
# get '/' do
# stream do |out|
# out.puts "still"
# sleep 1
# out.puts "streaming"
# end
# end
#
# Even works if #each is used to generate an Enumerator:
#
# def call(env)
# status, headers, body = @app.call(env)
# body = body.each.map { |s| s.upcase }
# [status, headers, body]
# end
#
# Note that both examples violate the Rack specification.
#
# == Setup
#
# In a classic application:
#
# require "sinatra"
# require "sinatra/streaming"
#
# In a modular application:
#
# require "sinatra/base"
# require "sinatra/streaming"
#
# class MyApp < Sinatra::Base
# helpers Sinatra::Streaming
# end
module Streaming
def stream(*)
stream = super
stream.extend Stream
stream.app = self
env['async.close'].callback { stream.close } if env.key? 'async.close'
stream
end
module Stream
attr_accessor :app, :lineno, :pos, :transformer, :closed
alias tell pos
alias closed? closed
def self.extended(obj)
obj.closed = false
obj.lineno = 0
obj.pos = 0
obj.callback { obj.closed = true }
obj.errback { obj.closed = true }
end
def <<(data)
raise IOError, 'not opened for writing' if closed?
@transformer ||= nil
data = data.to_s
data = @transformer[data] if @transformer
@pos += data.bytesize
super(data)
end
def each
# that way body.each.map { ... } works
return self unless block_given?
super
end
def map(&block)
# dup would not copy the mixin
clone.map!(&block)
end
def map!(&block)
@transformer ||= nil
if @transformer
inner = @transformer
outer = block
block = proc { |value| outer[inner[value]] }
end
@transformer = block
self
end
def write(data)
self << data
data.to_s.bytesize
end
alias syswrite write
alias write_nonblock write
def print(*args)
args.each { |arg| self << arg }
nil
end
def printf(format, *args)
print(format.to_s % args)
end
def putc(c)
print c.chr
end
def puts(*args)
args.each { |arg| self << "#{arg}\n" }
nil
end
def close_read
raise IOError, 'closing non-duplex IO for reading'
end
def closed_read?
true
end
def closed_write?
closed?
end
def external_encoding
Encoding.find settings.default_encoding
rescue NameError
settings.default_encoding
end
def settings
app.settings
end
def rewind
@pos = @lineno = 0
end
def not_open_for_reading(*)
raise IOError, 'not opened for reading'
end
alias bytes not_open_for_reading
alias eof? not_open_for_reading
alias eof not_open_for_reading
alias getbyte not_open_for_reading
alias getc not_open_for_reading
alias gets not_open_for_reading
alias read not_open_for_reading
alias read_nonblock not_open_for_reading
alias readbyte not_open_for_reading
alias readchar not_open_for_reading
alias readline not_open_for_reading
alias readlines not_open_for_reading
alias readpartial not_open_for_reading
alias sysread not_open_for_reading
alias ungetbyte not_open_for_reading
alias ungetc not_open_for_reading
private :not_open_for_reading
def enum_not_open_for_reading(*)
not_open_for_reading if block_given?
enum_for(:not_open_for_reading)
end
alias chars enum_not_open_for_reading
alias each_line enum_not_open_for_reading
alias each_byte enum_not_open_for_reading
alias each_char enum_not_open_for_reading
alias lines enum_not_open_for_reading
undef enum_not_open_for_reading
def dummy(*) end
alias flush dummy
alias fsync dummy
alias internal_encoding dummy
alias pid dummy
undef dummy
def seek(*)
0
end
alias sysseek seek
def sync
true
end
def tty?
false
end
alias isatty tty?
end
end
helpers Streaming
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/extension.rb | sinatra-contrib/lib/sinatra/extension.rb | # frozen_string_literal: true
require 'sinatra/base'
module Sinatra
# = Sinatra::Extension
#
# <tt>Sinatra::Extension</tt> is a mixin that provides some syntactic sugar
# for your extensions. It allows you to call almost any
# <tt>Sinatra::Base</tt> method directly inside your extension
# module. This means you can use +get+ to define a route, +before+
# to define a before filter, +set+ to define a setting and so on.
#
# Is important to be aware that this mixin remembers the method calls you
# make, and then, when your extension is registered, replays them on the
# Sinatra application that has been extended. In order to do that, it
# defines a <tt>registered</tt> method, so, if your extension defines one
# too, remember to call +super+.
#
# == Usage
#
# Just require the mixin and extend your extension with it:
#
# require 'sinatra/extension'
#
# module MyExtension
# extend Sinatra::Extension
#
# # set some settings for development
# configure :development do
# set :reload_stuff, true
# end
#
# # define a route
# get '/' do
# 'Hello World'
# end
#
# # The rest of your extension code goes here...
# end
#
# You can also create an extension with the +new+ method:
#
# MyExtension = Sinatra::Extension.new do
# # Your extension code goes here...
# end
#
# This is useful when you just want to pass a block to
# <tt>Sinatra::Base.register</tt>.
module Extension
def self.new(&block)
ext = Module.new.extend(self)
ext.class_eval(&block)
ext
end
def settings
self
end
def configure(*args, &block)
record(:configure, *args) { |c| c.instance_exec(c, &block) }
end
def registered(base = nil, &block)
base ? replay(base) : record(:class_eval, &block)
end
private
def record(method, *args, &block)
recorded_methods << [method, args, block]
end
def replay(object)
recorded_methods.each { |m, a, b| object.send(m, *a, &b) }
end
def recorded_methods
@recorded_methods ||= []
end
def method_missing(method, *args, &block)
return super unless Sinatra::Base.respond_to? method
record(method, *args, &block)
DontCall.new(method)
end
class DontCall < BasicObject
def initialize(method) @method = method end
def method_missing(*) raise "not supposed to use result of #{@method}!" end
def inspect; "#<#{self.class}: #{@method}>" end
end
end
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/link_header.rb | sinatra-contrib/lib/sinatra/link_header.rb | require 'sinatra/base'
module Sinatra
# = Sinatra::LinkHeader
#
# <tt>Sinatra::LinkHeader</tt> adds a set of helper methods to generate link
# HTML tags and their corresponding Link HTTP headers.
#
# == Usage
#
# Once you had set up the helpers in your application (see below), you will
# be able to call the following methods from inside your route handlers,
# filters and templates:
#
# +prefetch+::
# Sets the Link HTTP headers and returns HTML tags to prefetch the given
# resources.
#
# +stylesheet+::
# Sets the Link HTTP headers and returns HTML tags to use the given
# stylesheets.
#
# +link+::
# Sets the Link HTTP headers and returns the corresponding HTML tags
# for the given resources.
#
# +link_headers+::
# Returns the corresponding HTML tags for the current Link HTTP headers.
#
# === Classic Application
#
# In a classic application simply require the helpers, and start using them:
#
# require "sinatra"
# require "sinatra/link_header"
#
# # The rest of your classic application code goes here...
#
# === Modular Application
#
# In a modular application you need to require the helpers, and then tell
# the application you will use them:
#
# require "sinatra/base"
# require "sinatra/link_header"
#
# class MyApp < Sinatra::Base
# helpers Sinatra::LinkHeader
#
# # The rest of your modular application code goes here...
# end
#
module LinkHeader
##
# Sets Link HTTP header and returns HTML tags for telling the browser to
# prefetch given resources (only supported by Opera and Firefox at the
# moment).
def prefetch(*urls)
link(:prefetch, *urls)
end
##
# Sets Link HTTP header and returns HTML tags for using stylesheets.
def stylesheet(*urls)
urls << {} unless urls.last.respond_to? :to_hash
urls.last[:type] ||= mime_type(:css)
link(:stylesheet, *urls)
end
##
# Sets Link HTTP header and returns corresponding HTML tags.
#
# Example:
#
# # Sets header:
# # Link: </foo>; rel="next"
# # Returns String:
# # '<link href="/foo" rel="next" />'
# link '/foo', :rel => :next
#
# # Multiple URLs
# link :stylesheet, '/a.css', '/b.css'
def link(*urls)
opts = urls.last.respond_to?(:to_hash) ? urls.pop : {}
opts[:rel] = urls.shift unless urls.first.respond_to? :to_str
options = opts.map { |k, v| " #{k}=#{v.to_s.inspect}" }
html_pattern = "<link href=\"%s\"#{options.join} />"
http_pattern = ['<%s>', *options].join ';'
link = (response['Link'] ||= '')
link = response['Link'] = +link
urls.map do |url|
link << "," unless link.empty?
link << (http_pattern % url)
html_pattern % url
end.join
end
##
# Takes the current value of th Link header(s) and generates HTML tags
# from it.
#
# Example:
#
# get '/' do
# # You can of course use fancy helpers like #link, #stylesheet
# # or #prefetch
# response["Link"] = '</foo>; rel="next"'
# haml :some_page
# end
#
# __END__
#
# @@ layout
# %head= link_headers
# %body= yield
def link_headers
yield if block_given?
return '' unless response.include? 'Link'
response['Link'].split(",").map do |line|
url, *opts = line.split(';').map(&:strip)
"<link href=\"#{url[1..-2]}\" #{opts.join ' '} />"
end.join
end
def self.registered(_base)
puts "WARNING: #{self} is a helpers module, not an extension."
end
end
helpers LinkHeader
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/content_for.rb | sinatra-contrib/lib/sinatra/content_for.rb | # frozen_string_literal: true
require 'sinatra/base'
require 'sinatra/capture'
module Sinatra
# = Sinatra::ContentFor
#
# <tt>Sinatra::ContentFor</tt> is a set of helpers that allows you to capture
# blocks inside views to be rendered later during the request. The most
# common use is to populate different parts of your layout from your view.
#
# The currently supported engines are: Erb, Erubi, Haml and Slim.
#
# == Usage
#
# You call +content_for+, generally from a view, to capture a block of markup
# giving it an identifier:
#
# # index.erb
# <% content_for :some_key do %>
# <chunk of="html">...</chunk>
# <% end %>
#
# Then, you call +yield_content+ with that identifier, generally from a
# layout, to render the captured block:
#
# # layout.erb
# <%= yield_content :some_key %>
#
# If you have provided +yield_content+ with a block and no content for the
# specified key is found, it will render the results of the block provided
# to yield_content.
#
# # layout.erb
# <% yield_content :some_key_with_no_content do %>
# <chunk of="default html">...</chunk>
# <% end %>
#
# === Classic Application
#
# To use the helpers in a classic application all you need to do is require
# them:
#
# require "sinatra"
# require "sinatra/content_for"
#
# # Your classic application code goes here...
#
# === Modular Application
#
# To use the helpers in a modular application you need to require them, and
# then, tell the application you will use them:
#
# require "sinatra/base"
# require "sinatra/content_for"
#
# class MyApp < Sinatra::Base
# helpers Sinatra::ContentFor
#
# # The rest of your modular application code goes here...
# end
#
# == And How Is This Useful?
#
# For example, some of your views might need a few javascript tags and
# stylesheets, but you don't want to force this files in all your pages.
# Then you can put <tt><%= yield_content :scripts_and_styles %></tt> on your
# layout, inside the <head> tag, and each view can call <tt>content_for</tt>
# setting the appropriate set of tags that should be added to the layout.
#
# == Limitations
#
# Due to the rendering process limitation using <tt><%= yield_content %></tt>
# from within nested templates do not work above the <tt><%= yield %> statement.
# For more details https://github.com/sinatra/sinatra-contrib/issues/140#issuecomment-48831668
#
# # app.rb
# get '/' do
# erb :body, :layout => :layout do
# erb :foobar
# end
# end
#
# # foobar.erb
# <% content_for :one do %>
# <script>
# alert('one');
# </script>
# <% end %>
# <% content_for :two do %>
# <script>
# alert('two');
# </script>
# <% end %>
#
# Using <tt><%= yield_content %></tt> before <tt><%= yield %></tt> will cause only the second
# alert to display:
#
# # body.erb
# # Display only second alert
# <%= yield_content :one %>
# <%= yield %>
# <%= yield_content :two %>
#
# # body.erb
# # Display both alerts
# <%= yield %>
# <%= yield_content :one %>
# <%= yield_content :two %>
#
module ContentFor
include Capture
# Capture a block of content to be rendered later. For example:
#
# <% content_for :head do %>
# <script type="text/javascript" src="/foo.js"></script>
# <% end %>
#
# You can also pass an immediate value instead of a block:
#
# <% content_for :title, "foo" %>
#
# You can call +content_for+ multiple times with the same key
# (in the example +:head+), and when you render the blocks for
# that key all of them will be rendered, in the same order you
# captured them.
#
# Your blocks can also receive values, which are passed to them
# by <tt>yield_content</tt>
def content_for(key, value = nil, options = {}, &block)
block ||= proc { |*| value }
clear_content_for(key) if options[:flush]
content_blocks[key.to_sym] << capture_later(&block)
end
# Check if a block of content with the given key was defined. For
# example:
#
# <% content_for :head do %>
# <script type="text/javascript" src="/foo.js"></script>
# <% end %>
#
# <% if content_for? :head %>
# <span>content "head" was defined.</span>
# <% end %>
def content_for?(key)
content_blocks[key.to_sym].any?
end
# Unset a named block of content. For example:
#
# <% clear_content_for :head %>
def clear_content_for(key)
content_blocks.delete(key.to_sym) if content_for?(key)
end
# Render the captured blocks for a given key. For example:
#
# <head>
# <title>Example</title>
# <%= yield_content :head %>
# </head>
#
# Would render everything you declared with <tt>content_for
# :head</tt> before closing the <tt><head></tt> tag.
#
# You can also pass values to the content blocks by passing them
# as arguments after the key:
#
# <%= yield_content :head, 1, 2 %>
#
# Would pass <tt>1</tt> and <tt>2</tt> to all the blocks registered
# for <tt>:head</tt>.
def yield_content(key, *args, &block)
if block_given? && !content_for?(key)
haml? && Tilt[:haml] == Tilt::HamlTemplate && respond_to?(:capture_haml) ? capture_haml(*args, &block) : yield(*args)
else
content = content_blocks[key.to_sym].map { |b| capture(*args, &b) }
content.join.tap do |c|
if block_given? && (erb? || erubi?)
@_out_buf << c
end
end
end
end
private
def content_blocks
@content_blocks ||= Hash.new { |h, k| h[k] = [] }
end
end
helpers ContentFor
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/quiet_logger.rb | sinatra-contrib/lib/sinatra/quiet_logger.rb | # frozen_string_literal: true
module Sinatra
# = Sinatra::QuietLogger
#
# QuietLogger extension allows you to define paths excluded
# from logging using the +quiet_logger_prefixes+ setting.
# It is inspired from rails quiet_logger, but handles multiple paths.
#
# == Usage
#
# === Classic Application
#
# You have to require the quiet_logger, set the prefixes
# and register the extension in your application.
#
# require 'sinatra'
# require 'sinatra/quiet_logger'
#
# set :quiet_logger_prefixes, %w(css js images fonts)
# register Sinatra::QuietLogger
#
# === Modular Application
#
# The same for modular application:
#
# require 'sinatra/base'
# require 'sinatra/quiet_logger'
#
# set :quiet_logger_prefixes, %w(css js images fonts)
#
# class App < Sinatra::Base
# register Sinatra::QuietLogger
# end
#
module QuietLogger
def self.registered(app)
quiet_logger_prefixes = begin
app.settings.quiet_logger_prefixes.join('|')
rescue StandardError
''
end
return warn('You need to specify the paths you wish to exclude from logging via `set :quiet_logger_prefixes, %w(images css fonts)`') if quiet_logger_prefixes.empty?
const_set('QUIET_LOGGER_REGEX', %r(\A/{0,2}(?:#{quiet_logger_prefixes})))
::Rack::CommonLogger.prepend(
::Module.new do
def log(env, *)
super unless env['PATH_INFO'] =~ QUIET_LOGGER_REGEX
end
end
)
end
end
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/reloader.rb | sinatra-contrib/lib/sinatra/reloader.rb | # frozen_string_literal: true
require 'sinatra/base'
module Sinatra
# = Sinatra::Reloader
#
# <b>DEPRECATED:<b> Please consider using an alternative like
# <tt>rerun</tt> or <tt>rack-unreloader</tt> instead.
#
# Extension to reload modified files. Useful during development,
# since it will automatically require files defining routes, filters,
# error handlers and inline templates, with every incoming request,
# but only if they have been updated.
#
# == Usage
#
# === Classic Application
#
# To enable the reloader in a classic application all you need to do is
# require it:
#
# require "sinatra"
# require "sinatra/reloader" if development?
#
# # Your classic application code goes here...
#
# === Modular Application
#
# To enable the reloader in a modular application all you need to do is
# require it, and then, register it:
#
# require "sinatra/base"
# require "sinatra/reloader"
#
# class MyApp < Sinatra::Base
# configure :development do
# register Sinatra::Reloader
# end
#
# # Your modular application code goes here...
# end
#
# == Using the Reloader in Other Environments
#
# By default, the reloader is only enabled for the development
# environment. Similar to registering the reloader in a modular
# application, a classic application requires manually enabling the
# extension for it to be available in a non-development environment.
#
# require "sinatra"
# require "sinatra/reloader"
#
# configure :production do
# enable :reloader
# end
#
# == Changing the Reloading Policy
#
# You can refine the reloading policy with +also_reload+ and
# +dont_reload+, to customize which files should, and should not, be
# reloaded, respectively. You can also use +after_reload+ to execute a
# block after any file being reloaded.
#
# === Classic Application
#
# Simply call the methods:
#
# require "sinatra"
# require "sinatra/reloader" if development?
#
# also_reload '/path/to/some/file'
# dont_reload '/path/to/other/file'
# after_reload do
# puts 'reloaded'
# end
#
# # Your classic application code goes here...
#
# === Modular Application
#
# Call the methods inside the +configure+ block:
#
# require "sinatra/base"
# require "sinatra/reloader"
#
# class MyApp < Sinatra::Base
# configure :development do
# register Sinatra::Reloader
# also_reload '/path/to/some/file'
# dont_reload '/path/to/other/file'
# after_reload do
# puts 'reloaded'
# end
# end
#
# # Your modular application code goes here...
# end
#
module Reloader
# Watches a file so it can tell when it has been updated, and what
# elements does it contain.
class Watcher
# Represents an element of a Sinatra application that may need to
# be reloaded. An element could be:
# * a route
# * a filter
# * an error handler
# * a middleware
# * inline templates
#
# Its +representation+ attribute is there to allow to identify the
# element within an application, that is, to match it with its
# Sinatra's internal representation.
class Element < Struct.new(:type, :representation)
end
# Collection of file +Watcher+ that can be associated with a
# Sinatra application. That way, we can know which files belong
# to a given application and which files have been modified. It
# also provides a mechanism to inform a Watcher of the elements
# defined in the file being watched and if its changes should be
# ignored.
class List
@app_list_map = Hash.new { |hash, key| hash[key] = new }
# Returns the +List+ for the application +app+.
def self.for(app)
@app_list_map[app]
end
# Creates a new +List+ instance.
def initialize
@path_watcher_map = Hash.new do |hash, key|
hash[key] = Watcher.new(key)
end
end
# Lets the +Watcher+ for the file located at +path+ know that the
# +element+ is defined there, and adds the +Watcher+ to the +List+,
# if it isn't already there.
def watch(path, element)
watcher_for(path).elements << element
end
# Tells the +Watcher+ for the file located at +path+ to ignore
# the file changes, and adds the +Watcher+ to the +List+, if
# it isn't already there.
def ignore(path)
watcher_for(path).ignore
end
# Adds a +Watcher+ for the file located at +path+ to the
# +List+, if it isn't already there.
def watcher_for(path)
@path_watcher_map[File.expand_path(path)]
end
alias watch_file watcher_for
# Returns an array with all the watchers in the +List+.
def watchers
@path_watcher_map.values
end
# Returns an array with all the watchers in the +List+ that
# have been updated.
def updated
watchers.find_all(&:updated?)
end
end
attr_reader :path, :elements, :mtime
# Creates a new +Watcher+ instance for the file located at +path+.
def initialize(path)
@ignore = nil
@path = path
@elements = []
update
end
# Indicates whether or not the file being watched has been modified.
def updated?
!ignore? && !removed? && mtime != File.mtime(path)
end
# Updates the mtime of the file being watched.
def update
@mtime = File.mtime(path)
end
# Indicates whether or not the file being watched has inline
# templates.
def inline_templates?
elements.any? { |element| element.type == :inline_templates }
end
# Informs that the modifications to the file being watched
# should be ignored.
def ignore
@ignore = true
end
# Indicates whether or not the modifications to the file being
# watched should be ignored.
def ignore?
!!@ignore
end
# Indicates whether or not the file being watched has been removed.
def removed?
!File.exist?(path)
end
end
MUTEX_FOR_PERFORM = Mutex.new
# Allow a block to be executed after any file being reloaded
@@after_reload = []
def after_reload(&block)
@@after_reload << block
end
# When the extension is registered it extends the Sinatra application
# +klass+ with the modules +BaseMethods+ and +ExtensionMethods+ and
# defines a before filter to +perform+ the reload of the modified files.
def self.registered(klass)
@reloader_loaded_in ||= {}
return if @reloader_loaded_in[klass]
@reloader_loaded_in[klass] = true
klass.extend BaseMethods
klass.extend ExtensionMethods
klass.set(:reloader) { klass.development? }
klass.set(:reload_templates) { klass.reloader? }
klass.before do
if klass.reloader?
MUTEX_FOR_PERFORM.synchronize { Reloader.perform(klass) }
end
end
klass.set(:inline_templates, klass.app_file) if klass == Sinatra::Application
end
# Reloads the modified files, adding, updating and removing the
# needed elements.
def self.perform(klass)
reloaded_paths = []
Watcher::List.for(klass).updated.each do |watcher|
klass.set(:inline_templates, watcher.path) if watcher.inline_templates?
watcher.elements.each { |element| klass.deactivate(element) }
# Deletes all old elements.
watcher.elements.delete_if { true }
$LOADED_FEATURES.delete(watcher.path)
require watcher.path
watcher.update
reloaded_paths << watcher.path
end
return if reloaded_paths.empty?
@@after_reload.each do |block|
block.arity.zero? ? block.call : block.call(reloaded_paths)
end
# Prevents after_reload from increasing each time it's reloaded.
@@after_reload.delete_if do |blk|
path, = blk.source_location
path && reloaded_paths.include?(path)
end
end
# Contains the methods defined in Sinatra::Base that are overridden.
module BaseMethods
# Protects Sinatra::Base.run! from being called more than once.
def run!(*args)
if settings.reloader?
super unless running?
else
super
end
end
# Does everything Sinatra::Base#route does, but it also tells the
# +Watcher::List+ for the Sinatra application to watch the defined
# route.
#
# Note: We are using #compile! so we don't interfere with extensions
# changing #route.
def compile!(verb, path, block, **options)
source_location = block.respond_to?(:source_location) ?
block.source_location.first : caller_files[1]
signature = super
watch_element(
source_location, :route, { verb: verb, signature: signature }
)
signature
end
# Does everything Sinatra::Base#inline_templates= does, but it also
# tells the +Watcher::List+ for the Sinatra application to watch the
# inline templates in +file+ or the file who made the call to this
# method.
def inline_templates=(file = nil)
file = (caller_files[1] || File.expand_path($0)) if file.nil? || file == true
watch_element(file, :inline_templates)
super
end
# Does everything Sinatra::Base#use does, but it also tells the
# +Watcher::List+ for the Sinatra application to watch the middleware
# being used.
def use(middleware, *args, &block)
path = caller_files[1] || File.expand_path($0)
watch_element(path, :middleware, [middleware, args, block])
super
end
# Does everything Sinatra::Base#add_filter does, but it also tells
# the +Watcher::List+ for the Sinatra application to watch the defined
# filter.
def add_filter(type, path = nil, **options, &block)
source_location = block.respond_to?(:source_location) ?
block.source_location.first : caller_files[1]
result = super
watch_element(source_location, :"#{type}_filter", filters[type].last)
result
end
# Does everything Sinatra::Base#error does, but it also tells the
# +Watcher::List+ for the Sinatra application to watch the defined
# error handler.
def error(*codes, &block)
path = caller_files[1] || File.expand_path($0)
result = super
codes.each do |c|
watch_element(path, :error, code: c, handler: @errors[c])
end
result
end
# Does everything Sinatra::Base#register does, but it also lets the
# reloader know that an extension is being registered, because the
# elements defined in its +registered+ method need a special treatment.
def register(*extensions, &block)
start_registering_extension
result = super
stop_registering_extension
result
end
# Does everything Sinatra::Base#register does and then registers the
# reloader in the +subclass+.
def inherited(subclass)
result = super
subclass.register Sinatra::Reloader
result
end
end
# Contains the methods that the extension adds to the Sinatra application.
module ExtensionMethods
# Removes the +element+ from the Sinatra application.
def deactivate(element)
case element.type
when :route
verb = element.representation[:verb]
signature = element.representation[:signature]
(routes[verb] ||= []).delete(signature)
when :middleware
@middleware.delete(element.representation)
when :before_filter
filters[:before].delete(element.representation)
when :after_filter
filters[:after].delete(element.representation)
when :error
code = element.representation[:code]
handler = element.representation[:handler]
@errors.delete(code) if @errors[code] == handler
end
end
# Indicates with a +glob+ which files should be reloaded if they
# have been modified. It can be called several times.
def also_reload(*glob)
Dir[*glob].each { |path| Watcher::List.for(self).watch_file(path) }
end
# Indicates with a +glob+ which files should not be reloaded even if
# they have been modified. It can be called several times.
def dont_reload(*glob)
Dir[*glob].each { |path| Watcher::List.for(self).ignore(path) }
end
private
# attr_reader :register_path warn on -w (private attribute)
def register_path; @register_path ||= nil; end
# Indicates an extension is being registered.
def start_registering_extension
@register_path = caller_files[2]
end
# Indicates the extension has already been registered.
def stop_registering_extension
@register_path = nil
end
# Indicates whether or not an extension is being registered.
def registering_extension?
!register_path.nil?
end
# Builds a Watcher::Element from +type+ and +representation+ and
# tells the Watcher::List for the current application to watch it
# in the file located at +path+.
#
# If an extension is being registered, it also tells the list to
# watch it in the file where the extension has been registered.
# This prevents the duplication of the elements added by the
# extension in its +registered+ method with every reload.
def watch_element(path, type, representation = nil)
list = Watcher::List.for(self)
element = Watcher::Element.new(type, representation)
list.watch(path, element)
list.watch(register_path, element) if registering_extension?
end
end
end
register Reloader
Delegator.delegate :also_reload, :dont_reload
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/custom_logger.rb | sinatra-contrib/lib/sinatra/custom_logger.rb | # frozen_string_literal: true
module Sinatra
# = Sinatra::CustomLogger
#
# CustomLogger extension allows you to define your own logger instance
# using +logger+ setting. That logger then will be available
# as #logger helper method in your routes and views.
#
# == Usage
#
# === Classic Application
#
# To define your custom logger instance in a classic application:
#
# require 'sinatra'
# require 'sinatra/custom_logger'
# require 'logger'
#
# set :logger, Logger.new(STDOUT)
#
# get '/' do
# logger.info 'Some message' # STDOUT logger is used
# # Other code...
# end
#
# === Modular Application
#
# The same for modular application:
#
# require 'sinatra/base'
# require 'sinatra/custom_logger'
# require 'logger'
#
# class MyApp < Sinatra::Base
# helpers Sinatra::CustomLogger
#
# configure :development, :production do
# logger = Logger.new(File.open("#{root}/log/#{environment}.log", 'a'))
# logger.level = Logger::DEBUG if development?
# set :logger, logger
# end
#
# get '/' do
# logger.info 'Some message' # File-based logger is used
# # Other code...
# end
# end
#
module CustomLogger
def logger
if settings.respond_to?(:logger)
settings.logger
else
request.logger
end
end
end
helpers CustomLogger
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/contrib/version.rb | sinatra-contrib/lib/sinatra/contrib/version.rb | # frozen_string_literal: true
module Sinatra
module Contrib
VERSION = '4.2.1'
end
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/contrib/setup.rb | sinatra-contrib/lib/sinatra/contrib/setup.rb | # frozen_string_literal: true
require 'sinatra/base'
require 'sinatra/contrib/version'
module Sinatra
module Contrib
module Loader
def extensions
@extensions ||= { helpers: [], register: [] }
end
def register(name, path)
autoload name, path, :register
end
def helpers(name, path)
autoload name, path, :helpers
end
def autoload(name, path, method = nil)
extensions[method] << name if method
Sinatra.autoload(name, path)
end
def registered(base)
@extensions.each do |method, list|
list = list.map { |name| Sinatra.const_get name }
base.send(method, *list) unless base == ::Sinatra::Application
end
end
end
module Common
extend Loader
end
module Custom
extend Loader
end
module All
def self.registered(base)
base.register Common, Custom
end
end
extend Loader
def self.registered(base)
base.register Common, Custom
end
end
end
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
sinatra/sinatra | https://github.com/sinatra/sinatra/blob/074d876e0c54ffbe605bb733cefc5a71bb22dbc1/sinatra-contrib/lib/sinatra/contrib/all.rb | sinatra-contrib/lib/sinatra/contrib/all.rb | # frozen_string_literal: true
require 'sinatra/contrib'
Sinatra.register Sinatra::Contrib::All
| ruby | MIT | 074d876e0c54ffbe605bb733cefc5a71bb22dbc1 | 2026-01-04T15:37:42.068011Z | false |
matteocrippa/awesome-swift | https://github.com/matteocrippa/awesome-swift/blob/48e4464479e7701d4453730a07912ab84e787283/.github/convert.rb | .github/convert.rb | README = 'README.md'
CONTENTS = 'contents.json'
def get_json()
require 'json'
JSON.parse(File.read CONTENTS)
end
def output_linux(tags)
return '' if tags.nil?
return ':penguin: ' if tags.include? 'linux'
''
end
def output_projects(proj, id)
o = ''
proj.select {|p| p['category']==id }
.sort_by {|k,v| k['title'].downcase}
.each do |p|
o << "* [#{p['title']}](#{p['homepage']}) #{output_linux p['tags']}- #{p['description']}\n"
end
o
end
def output_content_category(c, indent)
toc = "\n"
for i in 1..indent
toc << '#'
end
toc << " #{c['title']}\n"
toc << "*#{c['description']}* " unless c['description'].nil?
toc << "[back to top](#readme) \n" if indent>2
toc << "\n"
toc
end
def output_content(j)
toc = ''
projects = j['projects']
parents, children = j['categories'].partition { |c| c['parent'].nil? }
parents.each do |c|
id = c['id']
toc << output_content_category(c, 2)
toc << output_projects(projects, id)
children.sort_by {|k,v| k['id']}
.select {|c| c['parent']==id}.each do |c|
child_id = c['id']
toc << output_content_category(c, 3)
toc << output_projects(projects, child_id)
children.sort_by {|k,v| k['id']}
.select {|c| c['parent']==child_id}.each do |c|
child_id = c['id']
toc << output_content_category(c, 4)
toc << output_projects(projects, c['id'])
children.sort_by {|k,v| k['id']}
.select {|c| c['parent']==child_id}.each do |c|
child_id = c['id']
toc << output_content_category(c, 5)
toc << output_projects(projects, c['id'])
end
end
end
end
toc
end
def output_header(j)
header = j['header']
app = j['ios_app_link']
num_projects = j['projects'].count
o = header
o << "\n\n"
o << output_table(app, num_projects)
o
end
def output_contributing(j)
o = "\n\n### Contributing\n\n"
o << j['header_contributing']
o
end
def output_partnership()
o = "\n\nIn parternship with:\n\n"
o << "[](https://codemo.tech/partners)"
o << "\n\n"
end
def output_table(ios_app_link, num_projects)
require 'date'
date = DateTime.now
date_display = date.strftime "%B %d, %Y"
o = "| Awesome | Linux | Projects | Updated |\n"
o << "|:-------:|:-----:|:--------:|:-------:|\n"
# row
o << '| [](https://github.com/sindresorhus/awesome) '
o << "| :penguin: | #{num_projects} | #{date_display} |"
# /row
o
end
def output_toc(j)
toc = "\n\n### Contents\n\n"
parents, children = j['categories'].partition { |c| c['parent'].nil? }
parents.each do |c|
id = c['id']
toc << "- [#{c['title']}](##{id})\n"
children.sort_by {|k,v| k['id']}
.select {|c| c['parent']==id}.each do |c|
child_id = c['id']
toc << " - [#{c['title']}](##{child_id})\n"
children.sort_by {|k,v| k['id']}
.select {|c| c['parent']==child_id}.each do |c|
child_id = c['id']
toc << " - [#{c['title']}](##{c['id']})\n"
children.sort_by {|k,v| k['id']}
.select {|c| c['parent']==child_id}.each do |c|
toc << " - [#{c['title']}](##{c['id']})\n"
end
end
end
end
toc
end
def write_readme(j, filename)
output = output_header(j)
output << output_partnership()
output << output_toc(j)
output << output_content(j)
output << output_contributing(j)
File.open(filename, 'w') { |f| f.write output}
puts "Wrote #{filename} :-)"
end
j = get_json()
write_readme(j, README)
| ruby | CC0-1.0 | 48e4464479e7701d4453730a07912ab84e787283 | 2026-01-04T15:37:27.381814Z | false |
greatghoul/remote-working | https://github.com/greatghoul/remote-working/blob/01dc10c52bb4b234bbaaa50692d99addd3d33ed1/scripts/contributors.rb | scripts/contributors.rb | #!/usr/bin/env ruby
require 'net/http'
require 'openssl'
require 'json'
API_HOST = 'api.github.com'.freeze
API_URL = '/repos/greatghoul/remote-working/stats/contributors'.freeze
http = Net::HTTP.new(API_HOST, 443)
http.use_ssl = true
response = http.send_request(
'GET', API_URL, nil,
Accept: 'application/vnd.github.v3+json'
)
contributors = JSON.parse(response.body)
contributors.map! do |contributor|
author = contributor['author']
Hash[{
login: author['login'],
avatar_url: author['avatar_url'],
url: author['url'],
commits: contributor['total']
}]
end
contributors.sort_by! { |contributor| -contributor[:commits] }
contributors.take(10).each do |contributor|
puts "<img src=\"#{contributor[:avatar_url]}\" width=\"18\" height=\"18\" " \
'style="vertical-align:middle;"> ' \
"<a href=\"#{contributor[:url]}\">#{contributor[:login]}</a> | " \
"#{contributor[:commits]}"
end
| ruby | MIT | 01dc10c52bb4b234bbaaa50692d99addd3d33ed1 | 2026-01-04T15:38:08.021240Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/tasks/changelog.rb | tasks/changelog.rb | # frozen_string_literal: true
# Changelog utility
class Changelog
ENTRIES_PATH = 'changelog/'
FIRST_HEADER = /#{Regexp.escape("## master (unreleased)\n")}/m.freeze
ENTRIES_PATH_TEMPLATE = "#{ENTRIES_PATH}%<type>s_%<name>s_%<timestamp>s.md"
TYPE_REGEXP = /#{Regexp.escape(ENTRIES_PATH)}([a-z]+)_/.freeze
TYPE_TO_HEADER = { new: 'New features', fix: 'Bug fixes', change: 'Changes' }.freeze
HEADER = /### (.*)/.freeze
PATH = 'CHANGELOG.md'
REF_URL = 'https://github.com/rubocop/rubocop'
MAX_LENGTH = 50
CONTRIBUTOR = '[@%<user>s]: https://github.com/%<user>s'
SIGNATURE = Regexp.new(format(Regexp.escape('[@%<user>s][]'), user: '([\w-]+)'))
EOF = "\n"
# New entry
Entry = Struct.new(:type, :body, :ref_type, :ref_id, :user, keyword_init: true) do
def initialize(type:, body: last_commit_title, ref_type: nil, ref_id: nil, user: github_user)
id, body = extract_id(body)
ref_id ||= id || 'x'
ref_type ||= id ? :issues : :pull
super
end
def write
File.write(path, content)
path
end
def path
format(
ENTRIES_PATH_TEMPLATE,
type: type, name: str_to_filename(body), timestamp: Time.now.strftime('%Y%m%d%H%M%S')
)
end
def content
period = '.' unless body.end_with? '.'
"* #{ref}: #{body}#{period} ([@#{user}][])\n"
end
def ref
"[##{ref_id}](#{REF_URL}/#{ref_type}/#{ref_id})"
end
def last_commit_title
`git log -1 --pretty=%B`.lines.first.chomp
end
def extract_id(body)
/^\[Fix(?:es)? #(\d+)\] (.*)/.match(body)&.captures || [nil, body]
end
def str_to_filename(str)
str
.split
.reject(&:empty?)
.map { |s| prettify(s) }
.inject do |result, word|
s = "#{result}_#{word}"
return result if s.length > MAX_LENGTH
s
end
end
def github_user
user = `git config --global credential.username`.chomp
if user.empty?
warn 'Set your username with `git config --global credential.username "myusernamehere"`'
end
user
end
private
def prettify(str)
str.gsub!(/\W/, '_')
# Separate word boundaries by `_`.
str.gsub!(/([A-Z]+)(?=[A-Z][a-z])|([a-z\d])(?=[A-Z])/) do
(Regexp.last_match(1) || Regexp.last_match(2)) << '_'
end
str.gsub!(/\A_+|_+\z/, '')
str.downcase!
str
end
end
def self.pending?
entry_paths.any?
end
def self.entry_paths
Dir["#{ENTRIES_PATH}*"]
end
def self.read_entries
entry_paths.to_h { |path| [path, File.read(path)] }
end
attr_reader :header, :rest
def initialize(content: File.read(PATH), entries: Changelog.read_entries)
require 'strscan'
parse(content)
@entries = entries
end
def and_delete!
@entries.each_key { |path| File.delete(path) }
end
def merge!
File.write(PATH, merge_content)
self
end
def unreleased_content
entry_map = parse_entries(@entries)
merged_map = merge_entries(entry_map)
merged_map.flat_map { |header, things| ["### #{header}\n", *things, ''] }.join("\n")
end
def merge_content
merged_content = [@header, unreleased_content, @rest.chomp, *new_contributor_lines].join("\n")
merged_content << EOF
end
def new_contributor_lines
unique_contributor_names = contributors.map { |user| format(CONTRIBUTOR, user: user) }.uniq
unique_contributor_names.reject { |line| @rest.include?(line) }
end
def contributors
contributors = @entries.values.flat_map do |entry|
entry.match(/\. \((?<contributors>.+)\)\n/)[:contributors].split(',')
end
contributors.join.scan(SIGNATURE).flatten
end
private
def merge_entries(entry_map)
all = @unreleased.merge(entry_map) { |_k, v1, v2| v1.concat(v2) }
canonical = TYPE_TO_HEADER.values.to_h { |v| [v, nil] }
canonical.merge(all).compact
end
def parse(content)
ss = StringScanner.new(content)
@header = ss.scan_until(FIRST_HEADER)
@unreleased = parse_release(ss.scan_until(/\n(?=## )/m))
@rest = ss.rest
end
# @return [Hash<type, Array<String>]]
def parse_release(unreleased)
unreleased
.lines
.map(&:chomp)
.reject(&:empty?)
.slice_before(HEADER)
.to_h do |header, *entries|
[HEADER.match(header)[1], entries]
end
end
def parse_entries(path_content_map)
changes = Hash.new { |h, k| h[k] = [] }
path_content_map.each do |path, content|
header = TYPE_TO_HEADER.fetch(TYPE_REGEXP.match(path)[1].to_sym)
changes[header].concat(content.lines.map(&:chomp))
end
changes
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/isolated_environment_spec.rb | spec/isolated_environment_spec.rb | # frozen_string_literal: true
RSpec.describe 'isolated environment', :isolated_environment, type: :feature do
include_context 'cli spec behavior'
let(:cli) { RuboCop::CLI.new }
# Configuration files above the work directory shall not disturb the
# tests. This is especially important on Windows where the temporary
# directory is under the user's home directory. On any platform we don't want
# a .rubocop.yml file in the temporary directory to affect the outcome of
# rspec.
#
# For this test, we shift the root_level down to the work directory so we
# can place a file above the root_level and ensure it is not loaded.
it 'is not affected by a config file above the work directory' do
ignored_path = File.expand_path(File.join(RuboCop::FileFinder.root_level, '.rubocop.yml'))
create_file(ignored_path, ['inherit_from: missing_file.yml'])
RuboCop::FileFinder.root_level = File.join(RuboCop::FileFinder.root_level, 'work')
create_file('ex.rb', ['# frozen_string_literal: true'])
# A return value of 0 means that the erroneous config file was not read.
expect(cli.run([])).to eq(0)
end
context 'bundler is isolated', :isolated_bundler do
it 'has a Gemfile path in the temporary directory' do
create_empty_file('Gemfile')
expect(Bundler::SharedHelpers.root.to_s).to eq(Dir.pwd)
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/project_spec.rb | spec/project_spec.rb | # frozen_string_literal: true
RSpec.describe 'RuboCop Project', type: :feature do
let(:cop_names) do
RuboCop::Cop::Registry
.global
.without_department(:InternalAffairs)
.reject { |cop| cop.cop_name.start_with?('Test/') }
.map(&:cop_name)
end
version_regexp = /\A\d+\.\d+\z|\A<<next>>\z/
describe 'default configuration file' do
matcher :match_all_cops do
def expected
%w[AllCops] + cop_names
end
match { |actual| (expected.to_set ^ actual.to_set).none? }
failure_message do
diff = RSpec::Support::Differ.new.diff_as_object(expected.sort, actual.sort)
"Cop registry does not match configuration keys.\n" \
'Check if a new cop is missing configuration, or if cops were accidentally ' \
"added to the registry in another test.\n\nDiff:\n#{diff}"
end
end
subject(:config) { RuboCop::ConfigLoader.load_file('config/default.yml') }
let(:configuration_keys) { config.keys }
it 'has configuration for all cops' do
expect(configuration_keys).to match_all_cops
end
it 'has a nicely formatted description for all cops' do
cop_names.each do |name|
description = config.dig(name, 'Description')
expect(description).not_to(be_nil, "`Description` configuration is required for `#{name}`.")
expect(description).not_to include("\n")
start_with_subject = description.match(/\AThis cop (?<verb>.+?) .*/)
suggestion = start_with_subject[:verb]&.capitalize if start_with_subject
suggestion ||= 'a verb'
expect(start_with_subject).to(be_nil,
"`Description` for `#{name}` should be started " \
"with `#{suggestion}` instead of `This cop ...`.")
end
end
it 'requires a nicely formatted `VersionAdded` metadata for all cops' do
cop_names.each do |name|
version = config.dig(name, 'VersionAdded')
expect(version).not_to(be_nil, "`VersionAdded` configuration is required for `#{name}`.")
expect(version).to(match(version_regexp),
"#{version} should be format ('X.Y' or '<<next>>') for #{name}.")
end
end
%w[VersionChanged VersionRemoved].each do |version_type|
it "requires a nicely formatted `#{version_type}` metadata for all cops" do
cop_names.each do |name|
version = config.dig(name, version_type)
next unless version
expect(version).to(match(version_regexp),
"#{version} should be format ('X.Y' or '<<next>>') for #{name}.")
end
end
end
it 'has a period at EOL of description' do
cop_names.each do |name|
next unless config[name]
description = config[name]['Description']
expect(description).to match(/\.\z/)
end
end
it 'sorts configuration keys alphabetically' do
expected = configuration_keys.sort
configuration_keys.each_with_index { |key, idx| expect(key).to eq expected[idx] }
end
# rubocop:disable RSpec/NoExpectationExample
it 'has a SupportedStyles for all EnforcedStyle and EnforcedStyle is valid' do
errors = []
cop_names.each do |name|
next unless config[name]
enforced_styles = config[name].select { |key, _| key.start_with?('Enforced') }
enforced_styles.each do |style_name, style|
supported_key = RuboCop::Cop::Util.to_supported_styles(style_name)
valid = config[name][supported_key]
unless valid
errors.push("#{supported_key} is missing for #{name}")
next
end
next if valid.include?(style)
errors.push("invalid #{style_name} '#{style}' for #{name} found")
end
end
raise errors.join("\n") unless errors.empty?
end
# rubocop:enable RSpec/NoExpectationExample
# rubocop:disable RSpec/NoExpectationExample
it 'does not have any duplication' do
fname = File.expand_path('../config/default.yml', __dir__)
content = File.read(fname)
RuboCop::YAMLDuplicationChecker.check(content, fname) do |key1, key2|
raise "#{fname} has duplication of #{key1.value} " \
"on line #{key1.start_line} and line #{key2.start_line}"
end
end
# rubocop:enable RSpec/NoExpectationExample
%w[Safe SafeAutoCorrect AutoCorrect].each do |metadata|
it "does not include `#{metadata}: true`" do
cop_names.each do |cop_name|
safe = config.dig(cop_name, metadata)
expect(safe).not_to be(true), "`#{cop_name}` has unnecessary `#{metadata}: true` config."
end
end
end
it 'does not include unnecessary `SafeAutoCorrect: false`' do
cop_names.each do |cop_name|
next unless config.dig(cop_name, 'Safe') == false
safe_autocorrect = config.dig(cop_name, 'SafeAutoCorrect')
expect(safe_autocorrect).not_to(
be(false), "`#{cop_name}` has unnecessary `SafeAutoCorrect: false` config."
)
end
end
it 'is expected that all cops documented with `@safety` are `Safe: false` or `SafeAutoCorrect: false`' do
require 'yard'
YARD::Registry.load!
unsafe_cops = YARD::Registry.all(:class).select do |example|
example.tags.any? { |tag| tag.tag_name == 'safety' }
end
unsafe_cop_names = unsafe_cops.map do |cop|
department_and_cop_names = cop.path.split('::')[2..] # Drop `RuboCop::Cop` from class name.
department_and_cop_names.join('/')
end
unsafe_cop_names.each do |cop_name|
cop_config = config[cop_name]
unsafe = cop_config['Safe'] == false || cop_config['SafeAutoCorrect'] == false
expect(unsafe).to(
be(true),
"`#{cop_name}` cop should be set `Safe: false` or `SafeAutoCorrect: false` " \
'because `@safety` YARD tag exists.'
)
end
end
end
describe 'cop message' do
let(:cops) { RuboCop::Cop::Registry.all }
it 'ends with a period or a question mark' do
cops.each do |cop|
begin
msg = cop.const_get(:MSG)
rescue NameError
next
end
expect(msg).to match(/(?:[.?]|(?:\[.+\])|%s)$/)
end
end
end
shared_examples 'has Changelog format' do
let(:lines) { changelog.each_line }
let(:non_reference_lines) { lines.take_while { |line| !line.start_with?('[@') } }
it 'has newline at end of file' do
expect(changelog).to end_with("\n")
end
it 'has either entries, headers, empty lines, or comments' do
expect(non_reference_lines).to all(match(/^(\*|#|$|<!---|-->| )/))
end
describe 'entry' do
it 'has a whitespace between the * and the body' do
expect(entries).to all(match(/^\* \S/))
end
it 'has one space between the period and the parentheses enclosing contributor name' do
# NOTE: For compatibility with outdated formats, if there's no contributor name,
# it checks that the line ends with a period.
expect(entries).to all(match(/(\. \(\[|\.\z)/))
end
describe 'link to related issue' do
let(:issues) do
entries.filter_map do |entry|
entry.match(%r{
(?<=^\*\s)
\[(?<ref>(?:(?<repo>rubocop/[a-z_-]+)?\#(?<number>\d+))|.*)\]
\((?<url>[^)]+)\)
}x)
end
end
it 'has a reference' do
issues.each { |issue| expect(issue[:ref]).not_to be_blank }
end
it 'has a valid issue number prefixed with #' do
issues.each { |issue| expect(issue[:number]).to match(/^\d+$/) }
end
it 'has a valid URL' do
issues.each do |issue|
number = issue[:number]&.gsub(/\D/, '')
repo = issue[:repo] || 'rubocop/rubocop'
pattern = %r{^https://github\.com/#{repo}/(?:issues|pull)/#{number}$}
expect(issue[:url]).to match(pattern)
end
end
it 'has a colon and a whitespace at the end' do
entries_including_issue_link = entries.select { |entry| entry.match(/^\*\s*\[/) }
expect(entries_including_issue_link).to all(include('): '))
end
end
it 'has a single space after each comma in the list of multiple contributor names' do
entries.each do |entry|
contributors = entry.scan(/\(\[@\S+\]\[\](?:, \[@\S+\]\[\])*\)/)
contributors.each do |contributor|
expect(contributor).not_to(
match(/,\S/),
"Contributor names should have exactly one space after each comma: #{contributor}"
)
end
end
end
describe 'contributor name' do
subject(:contributor_names) { lines.grep(/\A\[@/).map(&:chomp) }
it 'has a unique contributor name' do
expect(contributor_names.uniq.size).to eq contributor_names.size
end
end
describe 'body' do
let(:bodies) do
entries.map do |entry|
entry.gsub(/`[^`]+`/, '``').sub(/^\*\s*(?:\[.+?\):\s*)?/, '').sub(/\s*\([^)]+\)$/, '')
end
end
it 'does not start with a lower case' do
bodies.each { |body| expect(body).not_to match(/^[a-z]/) }
end
it 'ends with a punctuation' do
expect(bodies).to all(match(/[.!]$/))
end
it 'does not include a [Fix #x] directive' do
bodies.each { |body| expect(body).not_to match(/\[Fix(es)? \#.*?\]/i) }
end
end
end
end
describe 'Changelog' do
subject(:changelog) { File.read(path) }
let(:path) { File.expand_path('../CHANGELOG.md', __dir__) }
let(:entries) { lines.grep(/^\*/).map(&:chomp) }
# rubocop:disable RSpec/IncludeExamples
include_examples 'has Changelog format'
# rubocop:enable RSpec/IncludeExamples
context 'future entries' do
let(:allowed_cop_names) do
existing_cop_names.to_set.union(legacy_cop_names)
end
let(:existing_cop_names) do
RuboCop::Cop::Registry
.global
.reject { |cop| cop.cop_name.start_with?('Test/') }
.map(&:cop_name)
end
let(:legacy_cop_names) do
RuboCop::ConfigObsoletion.legacy_cop_names
end
dir = File.expand_path('../changelog', __dir__)
it 'does not have a directory' do
expect(Dir["#{dir}/*"]).to be_none { |path| File.directory?(path) }
end
Dir["#{dir}/*.md"].each do |path|
context "For #{path}" do
let(:path) { path }
# rubocop:disable RSpec/IncludeExamples
include_examples 'has Changelog format'
# rubocop:enable RSpec/IncludeExamples
it 'has a link to the issue or pull request address at the beginning' do
repo = 'rubocop/rubocop'
address_pattern = %r{\A\* \[#\d+\]\(https://github\.com/#{repo}/(issues|pull)/\d+\):}
expect(entries).to all(match(address_pattern))
end
it 'has a link to the contributors at the end' do
expect(entries).to all(match(/\(\[@\S+\]\[\](?:, \[@\S+\]\[\])*\)$/))
end
it 'has a single line' do
expect(File.foreach(path).count).to eq(1)
end
it 'starts with `new_`, `fix_`, or `change_`' do
expect(File.basename(path)).to(match(/\A(new|fix|change)_.+/))
end
it 'has valid cop name with backticks', :aggregate_failures do
entries.each do |entry|
entry.scan(%r{\b[A-Z]\w+(?:/[A-Z]\w+)+\b}) do |cop_name|
next if cop_name.split('/').first == 'AllCops'
expect(allowed_cop_names).to include(cop_name), "Invalid cop name #{cop_name}."
expect(entry).to include("`#{cop_name}`"), "Missing backticks for #{cop_name}."
end
end
end
it 'has cops in backticks with department', :aggregate_failures do
cop_names_without_department = allowed_cop_names.map { |name| name.split('/').last }
entries.each do |entry|
entry.scan(/`([A-Z]\w+)`/) do |cop_name, *|
expect(cop_names_without_department)
.not_to include(cop_name), "Missing department for #{cop_name}."
end
end
end
end
end
end
it 'has link definitions for all implicit links' do
implicit_link_names = changelog.scan(/\[([^\]]+)\]\[\]/).flatten.uniq
implicit_link_names.each do |name|
expect(changelog)
.to include("[#{name}]: http"), "missing a link for #{name}. " \
'Please add this link to the bottom of the file.'
end
end
context 'after version 0.14.0' do
let(:lines) { changelog.each_line.take_while { |line| !line.start_with?('## 0.14.0') } }
it 'has a link to the contributors at the end' do
expect(entries).to all(match(/\(\[@\S+\]\[\](?:, \[@\S+\]\[\])*\)$/))
end
end
end
describe 'requiring all of `lib` with verbose warnings enabled' do
it 'emits no warnings' do
warnings = `ruby -Ilib -w -W2 lib/rubocop.rb 2>&1`
.lines
.grep(%r{/lib/rubocop}) # ignore warnings from dependencies
expect(warnings).to eq []
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
# Disable colors in specs
require 'rainbow'
Rainbow.enabled = false
require_relative 'support/strict_warnings'
StrictWarnings.enable!
require 'rubocop'
require 'rubocop/cop/internal_affairs'
require 'rubocop/server'
require 'webmock/rspec'
require_relative 'core_ext/string'
begin
require 'pry'
rescue LoadError
# Pry is not activated.
end
# NOTE: To avoid executing processes needed only for extension plugins in `rubocop/rspec/support`,
# an environment variable is used to indicate that it is running in the RuboCop core development.
ENV['RUBOCOP_CORE_DEVELOPMENT'] = 'true'
# Require supporting files exposed for testing.
require 'rubocop/rspec/support'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].sort.each { |f| require f }
RSpec.configure do |config|
# This setting works together to allow you to limit a spec run
# to individual examples or groups you care about by tagging them with
# `:focus` metadata. When nothing is tagged with `:focus`, all examples
# get run.
unless defined?(TestQueue)
# See. https://github.com/tmm1/test-queue/issues/60#issuecomment-281948929
config.filter_run_when_matching :focus
end
config.example_status_persistence_file_path = 'spec/examples.txt'
config.order = :random
Kernel.srand config.seed
config.expect_with :rspec
config.mock_with :rspec
config.before(:suite) do
RuboCop::Cop::Registry.global.freeze
# This ensures that there are no side effects from running a particular spec.
# Use `:restore_registry` / `RuboCop::Cop::Registry.with_temporary_global` if
# need to modify registry (e.g. with `stub_cop_class`).
end
config.after(:suite) { RuboCop::Cop::Registry.reset! }
config.filter_run_excluding broken_on: :ruby_head if ENV['CI_RUBY_VERSION'] == 'head'
config.filter_run_excluding broken_on: :jruby if RUBY_ENGINE == 'jruby'
config.filter_run_excluding broken_on: :prism if ENV['PARSER_ENGINE'] == 'parser_prism'
# Prism supports Ruby 3.3+ parsing.
config.filter_run_excluding unsupported_on: :prism if ENV['PARSER_ENGINE'] == 'parser_prism'
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/tasks/changelog_spec.rb | spec/tasks/changelog_spec.rb | # frozen_string_literal: true
require_relative '../../tasks/changelog'
RSpec.describe Changelog do
subject(:changelog) do
list = entries.to_h { |e| [e.path, e.content] }
described_class.new(content: <<~CHANGELOG, entries: list)
# Change log
<!---
Do NOT edit this CHANGELOG.md file by hand directly, as it is automatically updated.
Please add an entry file to the https://github.com/rubocop/rubocop/blob/master/changelog/
named `{change_type}_{change_description}.md` if the new code introduces user-observable changes.
See https://github.com/rubocop/rubocop/blob/master/CONTRIBUTING.md#changelog-entry-format for details.
-->
## master (unreleased)
### New features
* [#bogus] Bogus feature
* [#bogus] Other bogus feature
## 0.7.1 (2020-09-28)
### Bug fixes
* [#127](https://github.com/rubocop/rubocop/pull/127): Fix dependency issue for JRuby. ([@marcandre][])
## 0.7.0 (2020-09-27)
### New features
* [#105](https://github.com/rubocop/rubocop/pull/105): `NodePattern` stuff...
* [#109](https://github.com/rubocop/rubocop/pull/109): Add `NodePattern` debugging rake tasks: `test_pattern`, `compile`, `parse`. See also [this app](https://nodepattern.herokuapp.com) ([@marcandre][])
* [#110](https://github.com/rubocop/rubocop/pull/110): Add `NodePattern` support for multiple terms unions. ([@marcandre][])
* [#111](https://github.com/rubocop/rubocop/pull/111): Optimize some `NodePattern`s by using `Set`s. ([@marcandre][])
* [#112](https://github.com/rubocop/rubocop/pull/112): Add `NodePattern` support for Regexp literals. ([@marcandre][])
more stuf....
[@marcandre]: https://github.com/marcandre
[@johndoexx]: https://github.com/johndoexx
CHANGELOG
end
let(:duplicate_entry) do
described_class::Entry.new(
type: :fix, body: 'Duplicate contributor name entry', user: 'johndoe'
)
end
let(:entries) do
%i[fix new fix].map.with_index do |type, i|
described_class::Entry.new(
type: type, body: "Do something cool#{'x' * i}", user: "johndoe#{'x' * i}"
)
end << duplicate_entry
end
describe Changelog::Entry do
subject(:entry) { described_class.new(type: type, body: body, user: github_user) }
let(:type) { :fix }
let(:github_user) { 'johndoe' }
describe '#content' do
context 'when there is an issue referenced' do
let(:body) { '[Fix #567] Do something cool.' }
it 'generates correct content' do
expect(entry.content).to eq <<~MD
* [#567](https://github.com/rubocop/rubocop/issues/567): Do something cool. ([@johndoe][])
MD
end
end
context 'when there is no issue referenced' do
let(:body) { 'Do something cool.' }
it 'generates correct content' do
expect(entry.content).to eq <<~MD
* [#x](https://github.com/rubocop/rubocop/pull/x): Do something cool. ([@johndoe][])
MD
end
end
end
describe '#ref_id' do
subject { entry.ref_id }
context 'when there is no body' do
let(:body) { '' }
it { is_expected.to eq('x') }
end
context 'when there is no issue referenced in the body' do
let(:body) { 'Fix something' }
it { is_expected.to eq('x') }
end
context 'when there is an issue referenced with [Fix #x] the body' do
let(:body) { '[Fix #123] Fix something' }
it { is_expected.to eq('123') }
end
context 'when there is an issue referenced with [Fixes #x] the body' do
let(:body) { '[Fixes #123] Fix something' }
it { is_expected.to eq('123') }
end
end
describe '#body' do
subject { entry.body }
context 'when there is no body' do
let(:body) { '' }
it { is_expected.to eq('') }
end
context 'when there is no issue referenced in the body' do
let(:body) { 'Fix something' }
it { is_expected.to eq('Fix something') }
end
context 'when there is an issue referenced with [Fix #x] the body' do
let(:body) { '[Fix #123] Fix something' }
it { is_expected.to eq('Fix something') }
end
context 'when there is an issue referenced with [Fixes #x] the body' do
let(:body) { '[Fixes #123] Fix something' }
it { is_expected.to eq('Fix something') }
end
end
describe '#path' do
it 'generates correct file name' do
body = 'Add new `Lint/UselessRescue` cop'
entry = described_class.new(type: :new, body: body, user: github_user)
expect(entry.path).to match(%r{\Achangelog/new_add_new_lint_useless_rescue_cop_\d+.md\z})
end
end
end
it 'parses correctly' do
expect(changelog.rest).to start_with('## 0.7.1 (2020-09-28)')
end
it 'merges correctly' do
expect(changelog.unreleased_content).to eq(<<~CHANGELOG)
### New features
* [#bogus] Bogus feature
* [#bogus] Other bogus feature
* [#x](https://github.com/rubocop/rubocop/pull/x): Do something coolx. ([@johndoex][])
### Bug fixes
* [#x](https://github.com/rubocop/rubocop/pull/x): Do something cool. ([@johndoe][])
* [#x](https://github.com/rubocop/rubocop/pull/x): Do something coolxx. ([@johndoexx][])
* [#x](https://github.com/rubocop/rubocop/pull/x): Duplicate contributor name entry. ([@johndoe][])
CHANGELOG
expect(changelog.new_contributor_lines).to eq(
[
'[@johndoe]: https://github.com/johndoe',
'[@johndoex]: https://github.com/johndoex'
]
)
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/empty_lines_around_body_shared_examples.rb | spec/support/empty_lines_around_body_shared_examples.rb | # frozen_string_literal: true
RSpec.shared_examples 'empty_lines_around_class_or_module_body' do |type|
context 'when EnforcedStyle is empty_lines_special' do
let(:cop_config) { { 'EnforcedStyle' => 'empty_lines_special' } }
context 'when first child is a method' do
it "requires blank line at the beginning and ending of #{type} body" do
expect_no_offenses(<<~RUBY)
#{type} SomeObject
def do_something; end
end
RUBY
end
context 'source without blank lines' do
it "registers an offense for #{type} not beginning and ending with a blank line" do
expect_offense(<<~RUBY)
#{type} SomeObject
def do_something; end
^ #{missing_begin}
end
^ #{missing_end}
RUBY
expect_correction(<<~RUBY)
#{type} SomeObject
def do_something; end
end
RUBY
end
end
context "when #{type} has a namespace" do
it 'requires no empty lines for namespace but ' \
"requires blank line at the beginning and ending of #{type} body" do
expect_no_offenses(<<~RUBY)
#{type} Parent
#{type} SomeObject
def do_something
end
end
end
RUBY
end
context 'source without blank lines' do
it 'registers and autocorrects the offenses' do
expect_offense(<<~RUBY)
#{type} Parent
#{type} SomeObject
def do_something
^ #{missing_begin}
end
end
^ #{missing_end}
end
RUBY
expect_correction(<<~RUBY)
#{type} Parent
#{type} SomeObject
def do_something
end
end
end
RUBY
end
end
context 'source with blank lines' do
it 'autocorrects the offenses' do
expect_offense(<<~RUBY)
#{type} Parent
^{} #{extra_begin}
#{type} SomeObject
def do_something
end
end
^{} #{extra_end}
end
RUBY
expect_correction(<<~RUBY)
#{type} Parent
#{type} SomeObject
def do_something
end
end
end
RUBY
end
end
end
end
context 'when first child is an access modifier' do
context "with blank lines at the beginning and ending of #{type} body" do
it 'registers no offense' do
expect_no_offenses(<<~RUBY)
#{type} SomeObject
private
def do_something; end
end
RUBY
end
end
context "with no blank lines at the beginning and ending of #{type} body" do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
#{type} SomeObject
private
^ #{missing_begin}
def do_something; end
end
^ #{missing_end}
RUBY
expect_correction(<<~RUBY)
#{type} SomeObject
private
def do_something; end
end
RUBY
end
end
end
context 'when first child is NOT a method' do
it "does not require blank line at the beginning of #{type} body " \
'but requires blank line before first def definition ' \
"and requires blank line at the end of #{type} body" do
expect_no_offenses(<<~RUBY)
#{type} SomeObject
include Something
def do_something; end
end
RUBY
end
context 'source without blank lines' do
it "registers an offense for #{type} not ending with a blank line" do
expect_offense(<<~RUBY)
#{type} SomeObject
include Something
def do_something; end
^ #{missing_def}
end
^ #{missing_end}
RUBY
expect_correction(<<~RUBY)
#{type} SomeObject
include Something
def do_something; end
end
RUBY
end
end
context 'source with blank lines' do
it "registers an offense for #{type} beginning with a blank line" do
expect_offense(<<~RUBY)
#{type} SomeObject
^{} #{extra_begin}
include Something
def do_something; end
^ #{missing_def}
end
RUBY
expect_correction(<<~RUBY)
#{type} SomeObject
include Something
def do_something; end
end
RUBY
end
end
context 'source with comment before method definition' do
it "registers an offense for #{type} beginning with a blank line" do
expect_offense(<<~RUBY)
#{type} SomeObject
^{} #{extra_begin}
include Something
# Comment
^ #{missing_def}
def do_something; end
end
RUBY
expect_correction(<<~RUBY)
#{type} SomeObject
include Something
# Comment
def do_something; end
end
RUBY
end
end
context "when #{type} has a namespace" do
it 'requires no empty lines for namespace ' \
"and does not require blank line at the beginning of #{type} body " \
"but requires blank line at the end of #{type} body" do
expect_no_offenses(<<~RUBY)
#{type} Parent
#{type} SomeObject
include Something
def do_something
end
end
end
RUBY
end
context 'source without blank lines' do
it 'registers and autocorrects the offenses' do
expect_offense(<<~RUBY)
#{type} Parent
#{type} SomeObject
include Something
def do_something
^ #{missing_def}
end
end
^ #{missing_end}
end
RUBY
expect_correction(<<~RUBY)
#{type} Parent
#{type} SomeObject
include Something
def do_something
end
end
end
RUBY
end
end
context 'source with blank lines' do
it 'registers and autocorrects the offenses' do
expect_offense(<<~RUBY)
#{type} Parent
^{} #{extra_begin}
#{type} SomeObject
^{} #{extra_begin}
include Something
def do_something
end
end
^{} #{extra_end}
end
RUBY
expect_correction(<<~RUBY)
#{type} Parent
#{type} SomeObject
include Something
def do_something
end
end
end
RUBY
end
end
context 'source with constants' do
it 'registers and autocorrects the offenses' do
expect_offense(<<~RUBY)
#{type} Parent
#{type} SomeObject
URL = %q(http://example.com)
def do_something
^ #{missing_def}
end
end
^ #{missing_end}
end
RUBY
expect_correction(<<~RUBY)
#{type} Parent
#{type} SomeObject
URL = %q(http://example.com)
def do_something
end
end
end
RUBY
end
end
end
end
context 'when namespace has multiple children' do
it 'requires empty lines for namespace' do
expect_no_offenses(<<~RUBY)
#{type} Parent
#{type} Mom
def do_something
end
end
#{type} Dad
end
end
RUBY
end
end
context "#{type} with only constants" do
it 'registers and autocorrects the offenses' do
expect_offense(<<~RUBY)
#{type} Parent
#{type} SomeObject
URL = %q(http://example.com)
WSDL = %q(http://example.com/wsdl)
end
^ #{missing_end}
end
RUBY
expect_correction(<<~RUBY)
#{type} Parent
#{type} SomeObject
URL = %q(http://example.com)
WSDL = %q(http://example.com/wsdl)
end
end
RUBY
end
end
context "#{type} with constant and child #{type}" do
it 'registers and autocorrects the offenses' do
expect_offense(<<~RUBY)
#{type} Parent
URL = %q(http://example.com)
#{type} SomeObject
^ #{missing_type}
def do_something; end
^ #{missing_begin}
end
^ #{missing_end}
end
^ #{missing_end}
RUBY
expect_correction(<<~RUBY)
#{type} Parent
URL = %q(http://example.com)
#{type} SomeObject
def do_something; end
end
end
RUBY
end
end
context "#{type} with empty body" do
context 'with empty line' do
let(:source) do
<<~RUBY
#{type} SomeObject
end
RUBY
end
it 'does NOT register offenses' do
expect_no_offenses(source)
end
end
context 'without empty line' do
let(:source) do
<<~RUBY
#{type} SomeObject
end
RUBY
end
it 'does NOT register offenses' do
expect_no_offenses(source)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/fake_location.rb | spec/support/fake_location.rb | # frozen_string_literal: true
# Tests may use this to fake out a location structure in an Offense.
FakeLocation = Struct.new(:line, :column, keyword_init: true)
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/strict_warnings.rb | spec/support/strict_warnings.rb | # frozen_string_literal: true
# NOTE: Prevents the cause from being obscured by `uninitialized constant StrictWarnings::StringIO`
# when there is a warning or syntax error in the product code.
require 'stringio'
# Ensure that RuboCop runs warning-free. This hooks into Ruby's `warn`
# method and raises when an unexpected warning is encountered.
module StrictWarnings
class WarningError < StandardError; end
# Warnings from 3rd-party gems, or other things that are unactionable
SUPPRESSED_WARNINGS = Regexp.union(
%r{lib/parser/builders/default.*Unknown escape},
%r{lib/parser/builders/default.*character class has duplicated range},
/Float.*out of range/, # also from the parser gem
/`Process` does not respond to `fork` method/, # JRuby
/File#readline accesses caller method's state and should not be aliased/, # JRuby, test stub
/instance variable @.* not initialized/, # Ruby 2.7
/\[server\] Unknown severity: UNKNOWN/, # RuboCop's built-in LSP API in spec
/`inspect_file` is deprecated\. Use `investigate` instead\./, # RuboCop's deprecated API in spec
/`forces` is deprecated./, # RuboCop's deprecated API in spec
/`support_autocorrect\?` is deprecated\./, # RuboCop's deprecated API in spec
/`Cop\.registry` is deprecated\./, # RuboCop's deprecated API in spec
/Specify `rubocop-internal_affairs` instead/ # RuboCop's obsolete internal plugin name
)
def warn(message, ...)
return if SUPPRESSED_WARNINGS.match?(message)
super
# RuboCop uses `warn` to display some of its output and tests assert against
# that. Assume that warnings are intentional when stderr is redirected.
return if $stderr.is_a?(StringIO)
# Ignore warnings from dev/rc ruby versions. Things are subject to change and
# contributors should not be bothered by them with red CI.
return if RUBY_PATCHLEVEL == -1
# Don't raise for warnings during development. It's expected that
# some code will warn like "unused variable" while iterating.
return unless ENV['STRICT_WARNINGS'] == '1'
raise WarningError, message
end
def self.enable!
$VERBOSE = true
Warning[:deprecated] = true
Warning.singleton_class.prepend(self)
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/lsp_helper.rb | spec/support/lsp_helper.rb | # frozen_string_literal: true
require 'rubocop/lsp/server'
module LSPHelper
def run_server_on_requests(*requests)
stdin = StringIO.new(requests.map { |request| to_jsonrpc(request) }.join)
RuboCop::Server::Helper.redirect(stdin: stdin) do
config_store = RuboCop::ConfigStore.new
RuboCop::LSP::Server.new(config_store).start
end
messages = parse_jsonrpc_messages($stdout)
[messages, $stderr]
end
def to_jsonrpc(hash)
hash_str = hash.to_json
"Content-Length: #{hash_str.bytesize}\r\n\r\n#{hash_str}"
end
def parse_jsonrpc_messages(io)
io.rewind
reader = LanguageServer::Protocol::Transport::Io::Reader.new(io)
messages = []
reader.read { |message| messages << message }
messages
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/suppress_pending_warning.rb | spec/support/suppress_pending_warning.rb | # frozen_string_literal: true
#
# This is a file that supports testing. An open class has been applied to
# `RuboCop::PendingCopsReporter.warn_on_pending_cops` to suppress pending cop
# warnings during testing.
#
module RuboCop
class PendingCopsReporter
class << self
remove_method :warn_on_pending_cops
def warn_on_pending_cops(config)
# noop
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/encoding_helper.rb | spec/support/encoding_helper.rb | # frozen_string_literal: true
# Overwrite the default internal/external encoding for the duration of a block.
# Ruby discourages this by emitting a warning when modifying, these helpers exist
# to suppress these warnings during tests.
module EncodingHelper
def with_default_internal_encoding(encoding)
orig_encoding = Encoding.default_internal
RuboCop::Util.silence_warnings { Encoding.default_internal = encoding }
yield
ensure
RuboCop::Util.silence_warnings { Encoding.default_internal = orig_encoding }
end
def with_default_external_encoding(encoding)
orig_encoding = Encoding.default_external
RuboCop::Util.silence_warnings { Encoding.default_external = encoding }
yield
ensure
RuboCop::Util.silence_warnings { Encoding.default_external = orig_encoding }
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/multiline_literal_brace_layout_method_argument_examples.rb | spec/support/multiline_literal_brace_layout_method_argument_examples.rb | # frozen_string_literal: true
RSpec.shared_examples 'multiline literal brace layout method argument' do
include MultilineLiteralBraceHelper
context 'when arguments to a method' do
let(:prefix) { 'bar(' }
let(:suffix) { ')' }
context 'and a comment after the last element' do
let(:b_comment) { ' # comment b' }
it 'detects closing brace on separate line from last element' do
expect_offense(<<~RUBY, close: close)
#{prefix}#{open}#{a},
#{b}#{b_comment}
%{close}
^{close} #{described_class::SAME_LINE_MESSAGE}
#{suffix}
RUBY
expect_no_corrections
end
end
context 'but no comment after the last element' do
it 'autocorrects the closing brace' do
expect_offense(<<~RUBY, close: close)
#{prefix}#{open}#{a},
#{b}
%{close}
^{close} #{described_class::SAME_LINE_MESSAGE}
#{suffix}
RUBY
expect_correction(<<~RUBY)
#{prefix}#{open}#{a},
#{b}#{close}
#{suffix}
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/cli_spec_behavior.rb | spec/support/cli_spec_behavior.rb | # frozen_string_literal: true
RSpec.shared_context 'cli spec behavior' do
include_context 'mock console output'
include FileHelper
def abs(path)
File.expand_path(path)
end
before do
RuboCop::ConfigLoader.debug = false
RuboCop::ConfigLoader.default_configuration = nil
# OPTIMIZE: Makes these specs faster. Work directory (the parent of
# .rubocop_cache) is removed afterwards anyway.
RuboCop::ResultCache.inhibit_cleanup = true
end
# Wrap all cli specs in `aggregate_failures` so that the expected and
# actual results of every expectation per example are shown. This is
# helpful because it shows information like expected and actual
# $stdout messages while not using `aggregate_failures` will only
# show information about expected and actual exit code
around { |example| aggregate_failures(&example) }
after { RuboCop::ResultCache.inhibit_cleanup = false }
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/multiline_literal_brace_layout_trailing_comma_examples.rb | spec/support/multiline_literal_brace_layout_trailing_comma_examples.rb | # frozen_string_literal: true
RSpec.shared_examples 'multiline literal brace layout trailing comma' do
let(:prefix) { '' } # A prefix before the opening brace.
let(:suffix) { '' } # A suffix for the line after the closing brace.
let(:a) { 'a' } # The first element.
let(:b) { 'b' } # The second element.
context 'symmetrical style' do
let(:cop_config) { { 'EnforcedStyle' => 'symmetrical' } }
context 'opening brace on same line as first element' do
context 'last element has a trailing comma' do
it 'autocorrects closing brace on different line from last element' do
expect_offense(<<~RUBY.chomp)
#{prefix}#{open}#{a}, # a
#{b}, # b
#{close}
^ #{same_line_message}
#{suffix}
RUBY
expect_correction(<<~RUBY.chomp)
#{prefix}#{open}#{a}, # a
#{b},#{close} # b
#{suffix}
RUBY
end
end
end
end
context 'same_line style' do
let(:cop_config) { { 'EnforcedStyle' => 'same_line' } }
context 'opening brace on same line as first element' do
context 'last element has a trailing comma' do
it 'autocorrects closing brace on different line as last element' do
expect_offense(<<~RUBY.chomp)
#{prefix}#{open}#{a}, # a
#{b}, # b
#{close}
^ #{always_same_line_message}
#{suffix}
RUBY
expect_correction(<<~RUBY.chomp)
#{prefix}#{open}#{a}, # a
#{b},#{close} # b
#{suffix}
RUBY
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/file_helper.rb | spec/support/file_helper.rb | # frozen_string_literal: true
require 'fileutils'
module FileHelper
# rubocop:disable Metrics/MethodLength
def create_file(file_path, content, retain_line_terminators: false)
file_path = File.expand_path(file_path)
# On Windows, when a file is opened in 'w' mode, LF line terminators (`\n`)
# are automatically converted to CRLF (`\r\n`).
# If this is not desired, `force_lf: true` will cause the file to be opened
# in 'wb' mode instead, which keeps existing line terminators.
file_mode = retain_line_terminators ? 'wb' : 'w'
ensure_descendant(file_path)
dir_path = File.dirname(file_path)
FileUtils.mkdir_p dir_path
File.open(file_path, file_mode) do |file|
break if content.nil?
case content
when String
file.puts content
when Array
file.puts content.join("\n")
end
end
file_path
end
# rubocop:enable Metrics/MethodLength
# rubocop:disable InternalAffairs/CreateEmptyFile
def create_empty_file(file_path)
create_file(file_path, '')
end
# rubocop:enable InternalAffairs/CreateEmptyFile
def create_link(link_path, target_path)
link_path = File.expand_path(link_path)
ensure_descendant(link_path)
dir_path = File.dirname(link_path)
FileUtils.mkdir_p dir_path
FileUtils.symlink(target_path, link_path)
end
def ensure_descendant(path, base = RuboCop::FileFinder.root_level)
return unless base
return if path.start_with?(base) && path != base
raise "Test file #{path} is outside of isolated_environment root #{base}"
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/condition_modifier_cop.rb | spec/support/condition_modifier_cop.rb | # frozen_string_literal: true
RSpec.shared_examples 'condition modifier cop' do |keyword, extra_message = nil|
let(:other_cops) { { 'Layout/LineLength' => { 'Max' => 80 } } }
context "for a multiline '#{keyword}'" do
it 'accepts it if single line would not fit on one line' do
# This statement is one character too long to fit.
condition = 'a' * (40 - keyword.length)
body = 'b' * 39
expect("#{body} #{keyword} #{condition}".length).to eq(81)
expect_no_offenses(<<~RUBY)
#{keyword} #{condition}
#{body}
end
RUBY
end
it 'accepts it if single line would not fit on one line and body last argument is a hash type with value omission', :ruby31 do
# This statement is one character too long to fit.
condition = 'a' * (40 - keyword.length)
body = "#{'b' * 35}(a:)"
expect("#{body} #{keyword} #{condition}".length).to eq(81)
expect_no_offenses(<<~RUBY)
#{keyword} #{condition}
#{body}
end
RUBY
end
context 'when Layout/LineLength is disabled' do
let(:other_cops) { { 'Layout/LineLength' => { 'Enabled' => false } } }
it 'registers an offense even for a long modifier statement' do
expect_offense(<<~RUBY, keyword: keyword)
%{keyword} foo
^{keyword} Favor modifier `#{keyword}` usage when having a single-line body.#{extra_message}
"This string would make the line longer than eighty characters if combined with the statement."
end
RUBY
end
end
it 'accepts it if body spans more than one line' do
expect_no_offenses(<<~RUBY)
#{keyword} some_condition
do_something
do_something_else
end
RUBY
end
it 'corrects it if result fits in one line' do
expect_offense(<<~RUBY, keyword: keyword)
%{keyword} condition
^{keyword} Favor modifier `#{keyword}` usage when having a single-line body.#{extra_message}
do_something
end
RUBY
expect_correction(<<~RUBY)
do_something #{keyword} condition
RUBY
end
it 'accepts an empty body' do
expect_no_offenses(<<~RUBY)
#{keyword} cond
end
RUBY
end
it 'accepts it when condition has local variable assignment' do
expect_no_offenses(<<~RUBY)
#{keyword} (var = something)
puts var
end
RUBY
end
it 'corrects it when assignment is in body' do
expect_offense(<<~RUBY, keyword: keyword)
%{keyword} true
^{keyword} Favor modifier `%{keyword}` usage when having a single-line body.#{extra_message}
x = 0
end
RUBY
expect_correction(<<~RUBY)
x = 0 #{keyword} true
RUBY
end
it "doesn't break when used as RHS of local var assignment" do
expect_offense(<<~RUBY, keyword: keyword)
a = %{keyword} b
^{keyword} Favor modifier `%{keyword}` usage when having a single-line body.#{extra_message}
1
end
RUBY
expect_correction(<<~RUBY)
a = (1 #{keyword} b)
RUBY
end
it "doesn't break when used as RHS of instance var assignment" do
expect_offense(<<~RUBY, keyword: keyword)
@a = %{keyword} b
^{keyword} Favor modifier `%{keyword}` usage when having a single-line body.#{extra_message}
1
end
RUBY
expect_correction(<<~RUBY)
@a = (1 #{keyword} b)
RUBY
end
it "doesn't break when used as RHS of class var assignment" do
expect_offense(<<~RUBY, keyword: keyword)
@@a = %{keyword} b
^{keyword} Favor modifier `%{keyword}` usage when having a single-line body.#{extra_message}
1
end
RUBY
expect_correction(<<~RUBY)
@@a = (1 #{keyword} b)
RUBY
end
it "doesn't break when used as RHS of constant assignment" do
expect_offense(<<~RUBY, keyword: keyword)
A = %{keyword} b
^{keyword} Favor modifier `%{keyword}` usage when having a single-line body.#{extra_message}
1
end
RUBY
expect_correction(<<~RUBY)
A = (1 #{keyword} b)
RUBY
end
it "doesn't break when used as RHS of binary arithmetic" do
expect_offense(<<~RUBY, keyword: keyword)
a + %{keyword} b
^{keyword} Favor modifier `%{keyword}` usage when having a single-line body.#{extra_message}
1
end
RUBY
expect_correction(<<~RUBY)
a + (1 #{keyword} b)
RUBY
end
it 'handles inline comments during autocorrection' do
expect_offense(<<~RUBY, keyword: keyword)
%{keyword} bar # important comment not to be nuked
^{keyword} Favor modifier `%{keyword}` usage when having a single-line body.#{extra_message}
baz
end
RUBY
expect_correction(<<~RUBY)
baz #{keyword} bar # important comment not to be nuked
RUBY
end
it 'handles one-line usage' do
expect_offense(<<~RUBY, keyword: keyword)
%{keyword} foo; bar; end
^{keyword} Favor modifier `%{keyword}` usage when having a single-line body.#{extra_message}
RUBY
expect_correction(<<~RUBY)
bar #{keyword} foo
RUBY
end
# See: https://github.com/rubocop/rubocop/issues/8273
context 'accepts multiline condition in modifier form' do
it 'registers an offense' do
expect_no_offenses(<<~RUBY)
foo #{keyword} bar ||
baz
RUBY
end
end
context 'when there is a comment on the first line and some code after the end keyword' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
[
1, #{keyword} foo # bar
baz
end, 3
]
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/multiline_literal_brace_helper.rb | spec/support/multiline_literal_brace_helper.rb | # frozen_string_literal: true
module MultilineLiteralBraceHelper
# Construct the source code for the braces. For instance, for an array
# the `open` brace would be `[` and the `close` brace would be `]`, so
# you could construct the following:
#
# braces(true, 'a', 'b', 'c', false)
#
# [ # line break indicated by `true` as the first argument.
# a,
# b,
# c] # no line break indicated by `false` as the last argument.
#
# This method also supports multi-line arguments. For example:
#
# braces(true, 'a', ['{', 'foo: bar', '}'], true)
#
# [ # line break indicated by `true` as the first argument.
# a,
# {
# foo: bar
# } # line break indicated by `true` as the last argument.
# ]
def braces(open_line_break, *args, close_line_break)
args = default_args if args.empty?
open + (open_line_break ? "\n" : '') +
args.map { |a| a.respond_to?(:join) ? a.join("\n") : a }.join(",\n") +
(close_line_break ? "\n" : '') + close
end
def default_args
[a, b + b_comment]
end
# Construct a piece of source code for brace layout testing. This farms
# out most of the work to `#braces` but it also includes a prefix and suffix.
def construct(*args)
"#{prefix}#{braces(*args)}\n#{suffix}"
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/multiline_literal_brace_layout_examples.rb | spec/support/multiline_literal_brace_layout_examples.rb | # frozen_string_literal: true
RSpec.shared_examples 'multiline literal brace layout' do
include MultilineLiteralBraceHelper
let(:prefix) { '' } # A prefix before the opening brace.
let(:suffix) { '' } # A suffix for the line after the closing brace.
let(:a) { 'a' } # The first element.
let(:b) { 'b' } # The second element.
let(:b_comment) { '' } # Comment after the second element.
let(:multi_prefix) { '' } # Prefix multi and heredoc with this.
let(:multi) do # A viable multi-line element.
<<~RUBY.chomp
{
foo: bar
}
RUBY
end
# This heredoc is unsafe to edit around because it ends on the same line as
# the node itself.
let(:heredoc) do
<<~RUBY.chomp
<<-EOM
baz
EOM
RUBY
end
# This heredoc is safe to edit around because it ends on a line before the
# last line of the node.
let(:safe_heredoc) do
<<~RUBY.chomp
{
a: <<-EOM
baz
EOM
}
RUBY
end
def make_multi(multi)
multi = multi.dup
multi[0] = multi_prefix + multi[0]
multi
end
context 'heredoc' do
let(:cop_config) { { 'EnforcedStyle' => 'same_line' } }
it 'ignores heredocs that could share a last line' do
expect_no_offenses(construct(false, a, make_multi(heredoc), true))
end
it 'detects heredoc structures that are safe to add to' do
expect_offense(<<~RUBY, close: close)
#{prefix}#{open}#{a},
#{multi_prefix}#{safe_heredoc}
%{close}
^{close} #{described_class::ALWAYS_SAME_LINE_MESSAGE}
#{suffix}
RUBY
expect_correction(<<~RUBY)
#{prefix}#{open}#{a},
#{multi_prefix}#{safe_heredoc}#{close}
#{suffix}
RUBY
end
end
context 'symmetrical style' do
let(:cop_config) { { 'EnforcedStyle' => 'symmetrical' } }
context 'opening brace on same line as first element' do
it 'allows closing brace on same line as last element' do
expect_no_offenses(construct(false, false))
end
it 'allows closing brace on same line as last multiline element' do
expect_no_offenses(construct(false, a, make_multi(multi), false))
end
it 'detects closing brace on different line from last element' do
expect_offense(<<~RUBY, close: close)
#{prefix}#{open}#{a},
#{b}#{b_comment}
%{close}
^{close} #{described_class::SAME_LINE_MESSAGE}
#{suffix}
RUBY
end
it 'autocorrects closing brace on different line from last element' do
expect_offense(<<~RUBY, close: close)
#{prefix}#{open}#{a}, # a
#{b} # b
%{close}
^{close} #{described_class::SAME_LINE_MESSAGE}
#{suffix}
RUBY
expect_correction(<<~RUBY)
#{prefix}#{open}#{a}, # a
#{b}#{close} # b
#{suffix}
RUBY
end
unless described_class == RuboCop::Cop::Layout::MultilineMethodDefinitionBraceLayout
context 'with a chained call on the closing brace' do
let(:suffix) { '.any?' }
context 'and a comment after the last element' do
let(:b_comment) { ' # comment b' }
it 'detects closing brace on separate line from last element' \
'but does not autocorrect the closing brace' do
expect_offense(<<~RUBY, close: close)
#{prefix}#{open}#{a},
#{b}#{b_comment}
%{close}
^{close} #{described_class::SAME_LINE_MESSAGE}
#{suffix}
RUBY
expect_no_corrections
end
end
context 'but no comment after the last element' do
it 'autocorrects the closing brace' do
expect_offense(<<~RUBY, close: close)
#{prefix}#{open}#{a},
#{b}
%{close}
^{close} #{described_class::SAME_LINE_MESSAGE}
#{suffix}
RUBY
expect_correction(<<~RUBY)
#{prefix}#{open}#{a},
#{b}#{close}
#{suffix}
RUBY
end
end
end
end
end
context 'opening brace on separate line from first element' do
it 'allows closing brace on separate line from last element' do
expect_no_offenses(construct(true, true))
end
it 'allows closing brace on separate line from last multiline element' do
expect_no_offenses(construct(true, a, make_multi(multi), true))
end
it 'detects closing brace on same line as last element' do
expect_offense(<<~RUBY.chomp, b: b, close: close)
#{prefix}#{open}
#{a},
%{b}%{close}
_{b}^{close} #{described_class::NEW_LINE_MESSAGE}
#{suffix}
RUBY
expect_correction(construct(true, true))
end
end
end
context 'new_line style' do
let(:cop_config) { { 'EnforcedStyle' => 'new_line' } }
context 'opening brace on same line as first element' do
it 'allows closing brace on different line from last element' do
expect_no_offenses(construct(false, true))
end
it 'allows closing brace on different line from multi-line element' do
expect_no_offenses(construct(false, a, make_multi(multi), true))
end
it 'detects closing brace on same line as last multiline element' do
expect_offense(<<~RUBY, multi_end: multi.lines.last.chomp, close: close)
#{prefix}#{open}#{a},
#{multi_prefix}#{multi}#{close}
_{multi_end}^{close} #{described_class::ALWAYS_NEW_LINE_MESSAGE}
#{suffix}
RUBY
end
it 'autocorrects closing brace on same line as last element' do
expect_offense(<<~RUBY, b: b, close: close)
#{prefix}#{open}#{a}, # a
%{b}%{close} # b
_{b}^{close} #{described_class::ALWAYS_NEW_LINE_MESSAGE}
#{suffix}
RUBY
expect_correction(<<~RUBY)
#{prefix}#{open}#{a}, # a
#{b}
#{close} # b
#{suffix}
RUBY
end
end
context 'opening brace on separate line from first element' do
it 'allows closing brace on separate line from last element' do
expect_no_offenses(construct(true, true))
end
it 'allows closing brace on separate line from last multiline element' do
expect_no_offenses(construct(true, a, make_multi(multi), true))
end
it 'detects closing brace on same line as last element' do
expect_offense(<<~RUBY, b: b, close: close)
#{prefix}#{open}
#{a},
%{b}%{close}
_{b}^{close} #{described_class::ALWAYS_NEW_LINE_MESSAGE}
#{suffix}
RUBY
expect_correction(<<~RUBY)
#{construct(true, true)}
RUBY
end
end
end
context 'same_line style' do
let(:cop_config) { { 'EnforcedStyle' => 'same_line' } }
context 'opening brace on same line as first element' do
it 'allows closing brace on same line from last element' do
expect_no_offenses(construct(false, false))
end
it 'allows closing brace on same line as multi-line element' do
expect_no_offenses(construct(false, a, make_multi(multi), false))
end
it 'detects closing brace on different line from multiline element' do
expect_offense(<<~RUBY, close: close)
#{prefix}#{open}#{a},
#{multi_prefix}#{multi}
%{close}
^{close} #{described_class::ALWAYS_SAME_LINE_MESSAGE}
#{suffix}
RUBY
end
it 'autocorrects closing brace on different line as last element' do
expect_offense(<<~RUBY, close: close)
#{prefix}#{open}#{a}, # a
#{b} # b
%{close}
^{close} #{described_class::ALWAYS_SAME_LINE_MESSAGE}
#{suffix}
RUBY
expect_correction(<<~RUBY)
#{prefix}#{open}#{a}, # a
#{b}#{close} # b
#{suffix}
RUBY
end
unless described_class == RuboCop::Cop::Layout::MultilineMethodDefinitionBraceLayout
context 'with a chained call on the closing brace' do
let(:suffix) { '.any?' }
context 'and a comment after the last element' do
let(:b_comment) { ' # comment b' }
it 'detects closing brace on separate line from last element' \
'but does not autocorrect the closing brace' do
expect_offense(<<~RUBY, close: close)
#{prefix}#{open}#{a},
#{b}#{b_comment}
%{close}
^{close} #{described_class::ALWAYS_SAME_LINE_MESSAGE}
#{suffix}
RUBY
expect_no_corrections
end
end
context 'but no comment after the last element' do
it 'autocorrects the closing brace' do
expect_offense(<<~RUBY, close: close)
#{prefix}#{open}#{a},
#{b}
%{close}
^{close} #{described_class::ALWAYS_SAME_LINE_MESSAGE}
#{suffix}
RUBY
expect_correction(<<~RUBY)
#{prefix}#{open}#{a},
#{b}#{close}
#{suffix}
RUBY
end
end
end
end
end
context 'opening brace on separate line from first element' do
it 'allows closing brace on same line as last element' do
expect_no_offenses(construct(true, false))
end
it 'allows closing brace on same line as last multiline element' do
expect_no_offenses(construct(true, a, make_multi(multi), false))
end
it 'detects closing brace on different line from last element' do
expect_offense(<<~RUBY, close: close)
#{prefix}#{open}
#{a},
#{b}#{b_comment}
%{close}
^{close} #{described_class::ALWAYS_SAME_LINE_MESSAGE}
#{suffix}
RUBY
expect_correction(<<~RUBY)
#{construct(true, false)}
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/custom_matchers.rb | spec/support/custom_matchers.rb | # frozen_string_literal: true
RSpec::Matchers.define :exit_with_code do |code|
supports_block_expectations
actual = nil
match do |block|
begin
block.call
rescue SystemExit => e
actual = e.status
end
actual && actual == code
end
failure_message do
"expected block to call exit(#{code}) but exit" +
(actual.nil? ? ' not called' : "(#{actual}) was called")
end
failure_message_when_negated { "expected block not to call exit(#{code})" }
description { "expect block to call exit(#{code})" }
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/misc_helper.rb | spec/support/misc_helper.rb | # frozen_string_literal: true
def trailing_whitespace
' '
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/alignment_examples.rb | spec/support/alignment_examples.rb | # frozen_string_literal: true
# `cop` and `source` must be declared with #let.
RSpec.shared_examples 'misaligned' do |annotated_source, used_style|
config_to_allow_offenses = if used_style
{ 'EnforcedStyleAlignWith' => used_style.to_s }
else
{ 'Enabled' => false }
end
annotated_source.split("\n\n").each do |chunk|
chunk << "\n" unless chunk.end_with?("\n")
source = chunk.lines.grep_v(/^ *\^/).join
name = source.gsub(/\n(?=[a-z ])/, ' <newline> ').gsub(/\s+/, ' ')
it "registers an offense for mismatched #{name} and autocorrects" do
expect_offense(chunk)
expect(cop.config_to_allow_offenses).to eq(config_to_allow_offenses)
raise if chunk !~ /\^\^\^ `end` at (\d), \d is not aligned with `.*` at \d, (\d)./
line_index = Integer(Regexp.last_match(1)) - 1
correct_indentation = ' ' * Integer(Regexp.last_match(2))
expect_correction(
source.lines[0...line_index].join +
"#{correct_indentation}#{source.lines[line_index].strip}\n"
)
end
end
end
RSpec.shared_examples 'aligned' do |alignment_base, arg, end_kw, name|
name ||= alignment_base
name = name.gsub("\n", ' <newline>')
it "accepts matching #{name} ... end" do
expect_no_offenses("#{alignment_base} #{arg}\n#{end_kw}")
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/cops/infinite_loop_during_autocorrect_with_change.rb | spec/support/cops/infinite_loop_during_autocorrect_with_change.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Test
class InfiniteLoopDuringAutocorrectWithChangeCop < RuboCop::Cop::Base
extend AutoCorrector
def on_class(node)
add_offense(node, message: 'Class must be a Module') do |corrector|
corrector.replace(node.loc.keyword, 'module')
end
end
def on_module(node)
add_offense(node, message: 'Module must be a Class') do |corrector|
# Will register an offense during the next loop again
corrector.replace(node, node.source)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/cops/b_to_a_cop.rb | spec/support/cops/b_to_a_cop.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Test
# This cop is only used to test infinite loop detection
class BtoA < RuboCop::Cop::Base
extend AutoCorrector
def on_class(node)
return unless node.loc.name.source.include?('B')
add_offense(node.loc.name, message: 'B to A') do |corrector|
autocorrect(corrector, node)
end
end
alias on_module on_class
private
def autocorrect(corrector, node)
corrector.replace(node.loc.name, node.loc.name.source.tr('B', 'A'))
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/cops/b_to_c_cop.rb | spec/support/cops/b_to_c_cop.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Test
# This cop is only used to test infinite loop detection
class BtoC < RuboCop::Cop::Base
extend AutoCorrector
def on_class(node)
return unless node.loc.name.source.include?('B')
add_offense(node.loc.name, message: 'B to C') do |corrector|
autocorrect(corrector, node)
end
end
alias on_module on_class
private
def autocorrect(corrector, node)
corrector.replace(node.loc.name, node.loc.name.source.tr('B', 'C'))
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/cops/c_to_a_cop.rb | spec/support/cops/c_to_a_cop.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Test
# This cop is only used to test infinite loop detection
class CtoA < RuboCop::Cop::Base
extend AutoCorrector
def on_class(node)
return unless node.loc.name.source.include?('C')
add_offense(node.loc.name, message: 'C to A') do |corrector|
autocorrect(corrector, node)
end
end
alias on_module on_class
private
def autocorrect(corrector, node)
corrector.replace(node.loc.name, node.loc.name.source.tr('C', 'A'))
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/cops/module_must_be_a_class_cop.rb | spec/support/cops/module_must_be_a_class_cop.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Test
class ModuleMustBeAClassCop < RuboCop::Cop::Base
extend AutoCorrector
def on_module(node)
add_offense(node, message: 'Module must be a Class') do |corrector|
corrector.replace(node.loc.keyword, 'class')
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/cops/class_must_be_a_module_cop.rb | spec/support/cops/class_must_be_a_module_cop.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Test
class ClassMustBeAModuleCop < RuboCop::Cop::Base
extend AutoCorrector
def on_class(node)
add_offense(node, message: 'Class must be a Module') do |corrector|
corrector.replace(node.loc.keyword, 'module')
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/cops/same_name_in_multiple_namespace.rb | spec/support/cops/same_name_in_multiple_namespace.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Test
class SameNameInMultipleNamespace < RuboCop::Cop::Base; end
module Foo
class SameNameInMultipleNamespace < RuboCop::Cop::Base; end
end
module Bar
class SameNameInMultipleNamespace < RuboCop::Cop::Base; end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/cops/infinite_loop_during_autocorrect.rb | spec/support/cops/infinite_loop_during_autocorrect.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Test
class InfiniteLoopDuringAutocorrectCop < RuboCop::Cop::Base
extend AutoCorrector
def on_class(node)
add_offense(node, message: 'Class must be a Module') do |corrector|
# Replace the offense with itself, will be picked up again next loop
corrector.replace(node, node.source)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/cops/alignment_directive.rb | spec/support/cops/alignment_directive.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Test
# This cop allows us to test the {AlignmentCorrector}. A node that is
# annotated with a comment of the form `# << delta` or `# >> delta` where
# `delta` is an integer will be shifted by `delta` columns in the
# indicated direction.
class AlignmentDirective < RuboCop::Cop::Base
extend AutoCorrector
MSG = 'Indent this node.'
def on_new_investigation
processed_source.ast_with_comments.each do |node, comments|
comments.each do |c|
if (delta = delta(c))
add_offense(node) { |corrector| autocorrect(corrector, node, c, delta) }
end
end
end
end
private
def autocorrect(corrector, node, comment, delta)
AlignmentCorrector.correct(corrector, processed_source, node, delta)
corrector.replace(comment, '#')
end
def delta(comment)
/\A#\s*(<<|>>)\s*(\d+)\s*\z/.match(comment.text) do |m|
(m[1] == '<<' ? -1 : 1) * m[2].to_i
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/support/cops/a_to_b_cop.rb | spec/support/cops/a_to_b_cop.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Test
# This cop is only used to test infinite loop detection
class AtoB < RuboCop::Cop::Base
extend AutoCorrector
def on_class(node)
return unless node.loc.name.source.include?('A')
add_offense(node.loc.name, message: 'A to B') do |corrector|
autocorrect(corrector, node)
end
end
alias on_module on_class
private
def autocorrect(corrector, node)
corrector.replace(node.loc.name, node.loc.name.source.tr('A', 'B'))
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/string_interpreter_spec.rb | spec/rubocop/string_interpreter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::StringInterpreter do
describe '.interpret' do
shared_examples 'simple escape' do |escaped|
it "handles #{escaped}" do
expect(described_class.interpret(escaped)).to eq escaped[1..]
end
end
it 'handles hex' do
expect(described_class.interpret('\\\\x68')).to eq('\x68')
end
it 'handles octal' do
expect(described_class.interpret('\\\\150')).to eq('\150')
end
it 'handles unicode' do
expect(described_class.interpret('\\\\u0068')).to eq('\u0068')
end
it 'handles extended unicode' do
expect(described_class.interpret('\\\\u{0068 0068}')).to eq('\\u{0068 0068}')
end
it_behaves_like 'simple escape', '\\\\a'
it_behaves_like 'simple escape', '\\\\b'
it_behaves_like 'simple escape', '\\\\e'
it_behaves_like 'simple escape', '\\\\f'
it_behaves_like 'simple escape', '\\\\n'
it_behaves_like 'simple escape', '\\\\r'
it_behaves_like 'simple escape', '\\\\s'
it_behaves_like 'simple escape', '\\\\t'
it_behaves_like 'simple escape', '\\\\v'
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/runner_formatter_invocation_spec.rb | spec/rubocop/runner_formatter_invocation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Runner, :isolated_environment do
describe 'how formatter is invoked' do
subject(:runner) { described_class.new({}, RuboCop::ConfigStore.new) }
include_context 'cli spec behavior'
let(:formatter) { instance_double(RuboCop::Formatter::BaseFormatter).as_null_object }
let(:output) { $stdout.string }
before do
create_file('2_offense.rb', '#' * 130)
create_file('5_offenses.rb', ['puts x ', 'test;', 'top;', '#' * 130])
create_file('no_offense.rb', '# frozen_string_literal: true')
allow(RuboCop::Formatter::SimpleTextFormatter).to receive(:new).and_return(formatter)
# avoid intermittent failure caused when another test set global
# options on ConfigLoader
RuboCop::ConfigLoader.clear_options
end
def run
runner.run([])
end
describe 'invocation order' do
let(:formatter) do
formatter = instance_spy(RuboCop::Formatter::BaseFormatter)
%i[started file_started file_finished finished output].each do |message|
allow(formatter).to receive(message) do
puts message unless message == :output
end
end
formatter
end
it 'is called in the proper sequence' do
run
expect(output).to eq(<<~OUTPUT)
started
file_started
file_finished
file_started
file_finished
file_started
file_finished
finished
OUTPUT
end
end
shared_examples 'sends all file paths' do |method_name|
it 'sends all file paths' do
expected_paths = [
'2_offense.rb',
'5_offenses.rb',
'no_offense.rb'
].map { |path| File.expand_path(path) }.sort
expect(formatter).to receive(method_name) do |all_files|
expect(all_files.sort).to eq(expected_paths)
end
run
end
describe 'the passed files paths' do
it 'is frozen' do
expect(formatter).to receive(method_name) do |all_files|
expect(all_files).to all(be_frozen)
end
run
end
end
end
describe '#started' do
it_behaves_like 'sends all file paths', :started
end
describe '#finished' do
context 'when RuboCop finished inspecting all files normally' do
it_behaves_like 'sends all file paths', :started
end
context 'when RuboCop is interrupted by user' do
it 'sends only processed file paths' do
class << formatter
attr_reader :reported_file_count
def file_finished(_file, _offenses)
@reported_file_count ||= 0
@reported_file_count += 1
end
end
class << runner
attr_reader :processed_file_count
def process_file(_file)
raise Interrupt if processed_file_count == 2
@processed_file_count ||= 0
@processed_file_count += 1
super
end
end
run
expect(formatter.reported_file_count).to eq(2)
end
end
end
shared_examples 'sends a file path' do |method_name|
it 'sends a file path' do
expect(formatter).to receive(method_name).with(File.expand_path('2_offense.rb'), anything)
expect(formatter).to receive(method_name).with(File.expand_path('5_offenses.rb'), anything)
expect(formatter).to receive(method_name).with(File.expand_path('no_offense.rb'), anything)
run
end
describe 'the passed path' do
it 'is frozen' do
expect(formatter).to receive(method_name).exactly(3).times do |path|
expect(path).to be_frozen
end
run
end
end
end
describe '#file_started' do
it_behaves_like 'sends a file path', :file_started
it 'sends file specific information hash' do
expect(formatter).to receive(:file_started)
.with(anything, an_instance_of(Hash)).exactly(3).times
run
end
end
describe '#file_finished' do
it_behaves_like 'sends a file path', :file_finished
it 'sends an array of detected offenses for the file' do
expect(formatter).to receive(:file_finished).exactly(3).times do |file, offenses|
case File.basename(file)
when '2_offense.rb'
expect(offenses.size).to eq(2)
when '5_offenses.rb'
expect(offenses.size).to eq(5)
when 'no_offense.rb'
expect(offenses).to be_empty
else
raise
end
expect(offenses).to all be_a(RuboCop::Cop::Offense)
end
run
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cops_documentation_generator_spec.rb | spec/rubocop/cops_documentation_generator_spec.rb | # frozen_string_literal: true
require 'rubocop/cops_documentation_generator'
RSpec.describe CopsDocumentationGenerator do
around do |example|
new_global = RuboCop::Cop::Registry.new([RuboCop::Cop::Style::HashSyntax])
RuboCop::Cop::Registry.with_temporary_global(new_global) { example.run }
end
it 'generates docs without errors' do
Dir.mktmpdir do |tmpdir|
generator = described_class.new(departments: %w[Style], base_dir: tmpdir)
expect do
generator.call
end.to output(%r{generated .*docs/modules/ROOT/pages/cops_style.adoc}).to_stdout
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/version_spec.rb | spec/rubocop/version_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Version do
include FileHelper
describe '.version' do
subject { described_class.version(debug: debug) }
context 'debug is false (default)' do
let(:debug) { false }
it { is_expected.to match(/\d+\.\d+\.\d+/) }
it { is_expected.not_to match(/\d+\.\d+\.\d+ \(using Parser/) }
end
context 'debug is true' do
let(:debug) { true }
it { is_expected.to match(/\d+\.\d+\.\d+ \(using Parser/) }
end
it 'is the gem version when called without arguments' do
expect(described_class.version).to eq(described_class::STRING)
end
end
describe '.extension_versions', :isolated_environment, :restore_configuration, :restore_registry do
subject(:extension_versions) { described_class.extension_versions(env) }
let(:env) { instance_double(RuboCop::CLI::Environment, config_store: config_store) }
let(:config_store) { RuboCop::ConfigStore.new }
before { RuboCop::ConfigLoader.clear_options }
context 'when no extensions are required' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
TargetRubyVersion: 2.7
YAML
end
it 'does not return any the extensions' do
expect(extension_versions).to eq([])
end
end
context 'when extensions are required' do
before do
create_file('.rubocop.yml', <<~YAML)
require:
- rubocop-performance
- rubocop-rspec
YAML
end
it 'returns the extensions' do
expect(extension_versions).to contain_exactly(
/- rubocop-performance \d+\.\d+\.\d+/,
/- rubocop-rspec \d+\.\d+\.\d+/
)
end
end
context 'when unknown extensions are required' do
before do
create_file('.rubocop.yml', <<~YAML)
require:
- ./rubocop-foobarbaz
YAML
create_file('rubocop-foobarbaz.rb', <<~RUBY)
module RuboCop
module FooBarBaz
end
end
RUBY
end
it 'does not return any the extensions' do
expect(extension_versions).to eq([])
end
end
context 'with an obsolete config' do
before do
create_file('.rubocop.yml', <<~YAML)
require:
- rubocop-performance
- rubocop-rspec
Style/MethodMissing:
Enabled: true
YAML
end
it 'returns the extensions' do
expect do
expect(extension_versions).to contain_exactly(
/- rubocop-performance \d+\.\d+\.\d+/,
/- rubocop-rspec \d+\.\d+\.\d+/
)
end.not_to raise_error
end
end
context 'when plugins are specified' do
before do
create_file('.rubocop.yml', <<~YAML)
plugins:
- rubocop-performance
- rubocop-rspec
YAML
end
it 'returns the extensions' do
expect(extension_versions).to contain_exactly(
/- rubocop-performance \d+\.\d+\.\d+/,
/- rubocop-rspec \d+\.\d+\.\d+/
)
end
end
context 'when a duplicate plugin is specified in an inherited config' do
before do
create_file('base.yml', <<~YAML)
plugins:
- rubocop-performance
YAML
create_file('.rubocop.yml', <<~YAML)
inherit_from:
- base.yml
plugins:
- rubocop-performance
- rubocop-rspec
YAML
end
it 'returns each extension exactly once' do
expect(extension_versions).to contain_exactly(
/- rubocop-performance \d+\.\d+\.\d+/,
/- rubocop-rspec \d+\.\d+\.\d+/
)
end
end
context 'with an invalid cop in config' do
before do
create_file('.rubocop.yml', <<~YAML)
require:
- rubocop-performance
- rubocop-rspec
Style/SomeCop:
Enabled: true
YAML
end
it 'returns the extensions' do
expect do
expect(extension_versions).to contain_exactly(
/- rubocop-performance \d+\.\d+\.\d+/,
/- rubocop-rspec \d+\.\d+\.\d+/
)
end.not_to raise_error
end
end
context 'with all known mappings' do
let(:config) { instance_double(RuboCop::Config) }
let(:known_features) do
%w[
rubocop-performance
rubocop-rspec
rubocop-graphql
rubocop-md
rubocop-thread_safety
rubocop-capybara
rubocop-factory_bot
rubocop-rspec_rails
]
end
before do
allow(config).to receive_messages(loaded_plugins: [], loaded_features: known_features)
allow(config_store).to receive(:for_dir).and_return(config)
stub_const('RuboCop::GraphQL::Version::STRING', '1.0.0')
stub_const('RuboCop::Markdown::Version::STRING', '1.0.0')
stub_const('RuboCop::ThreadSafety::Version::STRING', '1.0.0')
end
it 'returns the extensions' do
expect(extension_versions).to contain_exactly(
/- rubocop-performance \d+\.\d+\.\d+/,
/- rubocop-rspec \d+\.\d+\.\d+/,
/- rubocop-graphql \d+\.\d+\.\d+/,
/- rubocop-md \d+\.\d+\.\d+/,
/- rubocop-thread_safety \d+\.\d+\.\d+/
)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/lsp_spec.rb | spec/rubocop/lsp_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::LSP, :lsp do
describe '.enabled?' do
context 'when `RuboCop::LSP.enable` is called' do
before { described_class.enable }
it 'returns true' do
expect(described_class).to be_enabled
end
end
context 'when `RuboCop::LSP.disable` is called' do
before { described_class.disable }
it 'returns false' do
expect(described_class).not_to be_enabled
end
end
context 'when `RuboCop::LSP.disable` with block is called after `RuboCop::LSP.enable`' do
before do
described_class.enable
described_class.disable { @inner = described_class.enabled? }
@outer = described_class.enabled?
end
it 'returns false within block' do
expect(@inner).to be(false) # rubocop:disable RSpec/InstanceVariable
end
it 'returns true without block' do
expect(@outer).to be(true) # rubocop:disable RSpec/InstanceVariable
end
end
context 'when `RuboCop::LSP.disable` with block is called after `RuboCop::LSP.disable`' do
before do
described_class.disable
described_class.disable { @inner = described_class.enabled? }
@outer = described_class.enabled?
end
it 'returns false within block' do
expect(@inner).to be(false) # rubocop:disable RSpec/InstanceVariable
end
it 'returns false without block' do
expect(@outer).to be(false) # rubocop:disable RSpec/InstanceVariable
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/file_finder_spec.rb | spec/rubocop/file_finder_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::FileFinder, :isolated_environment do
include FileHelper
subject(:finder) { Class.new.include(described_class).new }
before do
create_empty_file('file')
create_empty_file(File.join('dir', 'file'))
end
describe '#find_file_upwards' do
it 'returns a file to be found upwards' do
expect(finder.find_file_upwards('file', 'dir')).to eq(File.expand_path('file', 'dir'))
expect(finder.find_file_upwards('file', Dir.pwd)).to eq(File.expand_path('file'))
end
it 'returns nil when file is not found' do
expect(finder.find_file_upwards('file2', 'dir')).to be_nil
end
context 'when searching for a file inside a directory' do
it 'returns a file to be found upwards' do
expect(finder.find_file_upwards('dir/file', Dir.pwd)).to eq(File.expand_path('file', 'dir'))
end
it 'returns nil when file is not found' do
expect(finder.find_file_upwards('dir2/file', Dir.pwd)).to be_nil
end
end
end
describe '#find_last_file_upwards' do
it 'returns the last file found upwards' do
expect(finder.find_last_file_upwards('file', 'dir')).to eq(File.expand_path('file'))
end
it 'returns nil when file is not found' do
expect(finder.find_last_file_upwards('xyz', 'dir')).to be_nil
end
end
describe '#traverse_directories_upwards' do
subject(:match_paths) do
matches = []
finder.traverse_directories_upwards(start_dir, stop_dir) do |dir|
matches << dir.expand_path.to_s
end
matches
end
let(:start_dir) { 'dir' }
context 'when not specifying the stop dir' do
let(:stop_dir) { nil }
it 'returns directories' do
expect(match_paths).to eq(
[File.expand_path(start_dir), File.expand_path('.'), File.expand_path('..')]
)
end
end
context 'when specifying the stop dir' do
let(:stop_dir) { "#{Dir.pwd}/dir" }
it 'respects the stop dir parameter' do
expect(match_paths).to eq([File.expand_path(start_dir)])
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/remote_config_spec.rb | spec/rubocop/remote_config_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::RemoteConfig do
include FileHelper
subject(:remote_config) { described_class.new(remote_config_url, base_dir).file }
let(:remote_config_url) { 'http://example.com/rubocop.yml' }
let(:base_dir) { '.' }
let(:cached_file_name) { '.rubocop-remote-e32e465e27910f2bc7262515eebe6b63.yml' }
let(:cached_file_path) { File.expand_path(cached_file_name, base_dir) }
before do
stub_request(:get, remote_config_url)
.to_return(status: 200, body: "Style/Encoding:\n Enabled: true")
end
after do
FileUtils.rm_rf cached_file_path
end
describe '.file' do
it 'downloads the file if the file does not exist' do
expect(remote_config).to eq(cached_file_path)
expect(File).to exist(cached_file_path)
end
it 'does not download the file if cache lifetime has not been reached' do
FileUtils.touch cached_file_path, mtime: Time.now - ((60 * 60) * 20)
expect(remote_config).to eq(cached_file_path)
assert_not_requested :get, remote_config_url
end
it 'downloads the file if cache lifetime has been reached' do
FileUtils.touch cached_file_path, mtime: Time.now - ((60 * 60) * 30)
expect(remote_config).to eq(cached_file_path)
assert_requested :get, remote_config_url
end
context 'when the remote URL is not a valid URI' do
let(:remote_config_url) { 'http://example.com/rΓΌbocop.yml' }
it 'raises a configuration error' do
expect do
remote_config
end.to raise_error(RuboCop::ConfigNotFoundError, /is not a valid URI/)
end
end
context 'when remote URL is configured with token auth' do
let(:token) { 'personal_access_token' }
let(:remote_config_url) { "http://#{token}@example.com/rubocop.yml" }
let(:stripped_remote_config_url) { 'http://example.com/rubocop.yml' }
let(:cached_file_name) { '.rubocop-remote-ab4a54bcd0d0314614a65a4394745105.yml' }
before do
stub_request(:get, stripped_remote_config_url)
.with(basic_auth: [token])
.to_return(status: 200, body: "Style/Encoding:\n Enabled: true")
end
it 'downloads the file if the file does not exist' do
expect(remote_config).to eq(cached_file_path)
expect(File).to exist(cached_file_path)
end
it 'does not download the file if cache lifetime has not been reached' do
FileUtils.touch cached_file_path, mtime: Time.now - ((60 * 60) * 20)
expect(remote_config).to eq(cached_file_path)
assert_not_requested :get, remote_config_url
end
it 'downloads the file if cache lifetime has been reached' do
FileUtils.touch cached_file_path, mtime: Time.now - ((60 * 60) * 30)
expect(remote_config).to eq(cached_file_path)
assert_requested :get, stripped_remote_config_url
end
context 'when the remote URL responds with 404' do
before do
stub_request(:get, stripped_remote_config_url).to_return(status: 404)
end
it 'raises error' do
expect do
remote_config
end.to raise_error(Net::HTTPClientException,
'404 "" while downloading remote config file http://example.com/rubocop.yml')
end
end
end
context 'when remote URL is configured with basic auth' do
let(:username) { 'username' }
let(:password) { 'password' }
let(:remote_config_url) { "http://#{username}:#{password}@example.com/rubocop.yml" }
let(:stripped_remote_config_url) { 'http://example.com/rubocop.yml' }
let(:cached_file_name) { '.rubocop-remote-4a2057b5f7fe601a137248a7cfe411d1.yml' }
before do
stub_request(:get, stripped_remote_config_url)
.with(basic_auth: [username, password])
.to_return(status: 200, body: "Style/Encoding:\n Enabled: true")
end
it 'downloads the file if the file does not exist' do
expect(remote_config).to eq(cached_file_path)
expect(File).to exist(cached_file_path)
end
it 'does not download the file if cache lifetime has not been reached' do
FileUtils.touch cached_file_path, mtime: Time.now - ((60 * 60) * 20)
expect(remote_config).to eq(cached_file_path)
assert_not_requested :get, remote_config_url
end
it 'downloads the file if cache lifetime has been reached' do
FileUtils.touch cached_file_path, mtime: Time.now - ((60 * 60) * 30)
expect(remote_config).to eq(cached_file_path)
assert_requested :get, stripped_remote_config_url
end
context 'when the remote URL responds with 404' do
before do
stub_request(:get, stripped_remote_config_url).to_return(status: 404)
end
it 'raises error' do
expect do
remote_config
end.to raise_error(Net::HTTPClientException,
'404 "" while downloading remote config file http://example.com/rubocop.yml')
end
end
context 'when the remote URL responds with 500' do
before { stub_request(:get, stripped_remote_config_url).to_return(status: 500) }
it 'raises error' do
expect do
remote_config
end.to raise_error(Net::HTTPFatalError,
'500 "" while downloading remote config file http://example.com/rubocop.yml')
end
end
end
context 'when the remote URL responds with redirect' do
let(:new_location) { 'http://cdn.example.com/rubocop.yml' }
before do
stub_request(:get, remote_config_url).to_return(headers: { 'Location' => new_location })
stub_request(:get, new_location)
.to_return(status: 200, body: "Style/Encoding:\n Enabled: true")
end
it 'follows the redirect and downloads the file' do
expect(remote_config).to eq(cached_file_path)
expect(File).to exist(cached_file_path)
end
end
context 'when the remote URL responds with not modified' do
before { stub_request(:get, remote_config_url).to_return(status: 304) }
it 'reuses the existing cached file' do
FileUtils.touch cached_file_path, mtime: Time.now - ((60 * 60) * 30)
expect { remote_config }.not_to change(File.stat(cached_file_path), :mtime)
assert_requested :get, remote_config_url
end
end
context 'when the network is inaccessible' do
before { stub_request(:get, remote_config_url).to_raise(SocketError) }
it 'reuses the existing cached file' do
expect(remote_config).to eq(cached_file_path)
end
end
context 'when the remote URL responds with 500' do
before { stub_request(:get, remote_config_url).to_return(status: 500) }
it 'raises error' do
expect do
remote_config
end.to raise_error(Net::HTTPFatalError,
'500 "" while downloading remote config file http://example.com/rubocop.yml')
end
end
end
describe '.inherit_from_remote' do
context 'when the remote includes file starting with `./`' do
let(:includes_file) { './base.yml' }
it 'returns remote includes URI' do
remote_config = described_class.new(remote_config_url, base_dir)
includes_config = remote_config.inherit_from_remote(includes_file)
expect(includes_config.uri).to eq URI.parse('http://example.com/base.yml')
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/config_regeneration_spec.rb | spec/rubocop/config_regeneration_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::ConfigRegeneration, :isolated_environment do
include FileHelper
subject(:config_regeneration) { described_class.new }
describe '#options' do
subject { config_regeneration.options }
context 'when no todo file exists' do
it { is_expected.to eq(auto_gen_config: true) }
end
context 'when there is a blank todo file' do
before { create_file('.rubocop_todo.yml', nil) }
it { is_expected.to eq(auto_gen_config: true) }
end
context 'when the todo file is malformed' do
before { create_file('.rubocop_todo.yml', 'todo') }
it { is_expected.to eq(auto_gen_config: true) }
end
context 'it parses options from the generation comment' do
let(:header) do
<<~HEADER
# This configuration was generated by
# `rubocop --auto-gen-config --auto-gen-only-exclude --exclude-limit 100 --no-offense-counts --no-auto-gen-timestamp`
# on 2020-06-12 17:42:47 UTC using RuboCop version 0.85.1.
HEADER
end
let(:expected_options) do
{
auto_gen_config: true,
auto_gen_only_exclude: true,
exclude_limit: '100',
offense_counts: false,
auto_gen_timestamp: false
}
end
before { create_file('.rubocop_todo.yml', header) }
it { is_expected.to eq(expected_options) }
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/magic_comment_spec.rb | spec/rubocop/magic_comment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::MagicComment do
shared_examples 'magic comment' do |comment, expectations = {}|
encoding = expectations[:encoding]
frozen_string = expectations[:frozen_string_literal]
shareable_constant_value = expectations[:shareable_constant_value]
typed = expectations[:typed]
it "returns #{encoding.inspect} for encoding when comment is #{comment}" do
expect(described_class.parse(comment).encoding).to eql(encoding)
end
it "returns #{frozen_string.inspect} for frozen_string_literal when comment is #{comment}" do
expect(described_class.parse(comment).frozen_string_literal).to eql(frozen_string)
end
it "returns #{shareable_constant_value.inspect} for shareable_constant_value " \
"when comment is #{comment}" do
expect(described_class.parse(comment)
.shareable_constant_value).to eql(shareable_constant_value)
end
it "returns #{typed.inspect} for typed when comment is #{comment}" do
expect(described_class.parse(comment).typed).to eql(typed)
end
end
it_behaves_like 'magic comment', '#'
it_behaves_like 'magic comment', '# encoding: utf-8', encoding: 'utf-8'
it_behaves_like 'magic comment', '# ENCODING: utf-8', encoding: 'utf-8'
it_behaves_like 'magic comment', '# eNcOdInG: utf-8', encoding: 'utf-8'
it_behaves_like 'magic comment', '# coding: utf-8', encoding: 'utf-8'
it_behaves_like 'magic comment', ' # coding: utf-8', encoding: 'utf-8'
it_behaves_like 'magic comment', '# incoding: utf-8'
it_behaves_like 'magic comment',
'# encoding: stateless-iso-2022-jp-kddi',
encoding: 'stateless-iso-2022-jp-kddi'
it_behaves_like 'magic comment', '# frozen_string_literal: true', frozen_string_literal: true
it_behaves_like 'magic comment', ' # frozen_string_literal: true', frozen_string_literal: true
it_behaves_like 'magic comment', '# frozen_string_literal:true', frozen_string_literal: true
it_behaves_like 'magic comment', '# frozen_string_literal: false', frozen_string_literal: false
it_behaves_like 'magic comment', '# frozen-string-literal: true', frozen_string_literal: true
it_behaves_like 'magic comment', '# FROZEN-STRING-LITERAL: true', frozen_string_literal: true
it_behaves_like 'magic comment', '# fRoZeN-sTrInG_lItErAl: true', frozen_string_literal: true
it_behaves_like 'magic comment', '# shareable_constant_value: literal', shareable_constant_value: 'literal'
it_behaves_like 'magic comment', '# shareable_constant_value:literal', shareable_constant_value: 'literal'
it_behaves_like 'magic comment', '# shareable-constant-value: literal', shareable_constant_value: 'literal'
it_behaves_like 'magic comment', '# SHAREABLE-CONSTANT-VALUE: literal', shareable_constant_value: 'literal'
it_behaves_like 'magic comment', '# sHaReaBLE-CoNstANT-ValUE: literal', shareable_constant_value: 'literal'
it_behaves_like 'magic comment', '# shareable_constant_value: none', shareable_constant_value: 'none'
it_behaves_like 'magic comment', '# xyz shareable_constant_value: literal'
it_behaves_like 'magic comment', '# xyz shareable_constant_value: literal xyz'
it_behaves_like 'magic comment', '# typed: ignore', typed: 'ignore'
it_behaves_like 'magic comment', '# typed: false', typed: 'false'
it_behaves_like 'magic comment', '# typed: true', typed: 'true'
it_behaves_like 'magic comment', '# typed: strict', typed: 'strict'
it_behaves_like 'magic comment', '# typed: strong', typed: 'strong'
it_behaves_like 'magic comment', '#typed:strict', typed: 'strict'
it_behaves_like 'magic comment', '# typed:strict', typed: 'strict'
it_behaves_like 'magic comment', '# @typed'
it_behaves_like(
'magic comment',
'# shareable_constant_value: experimental_everything',
shareable_constant_value: 'experimental_everything'
)
it_behaves_like(
'magic comment',
'# shareable_constant_value: experimental_copy',
shareable_constant_value: 'experimental_copy'
)
it_behaves_like 'magic comment',
'# -*- frozen-string-literal: true -*-',
frozen_string_literal: true
it_behaves_like 'magic comment',
'# frozen_string_literal: invalid',
frozen_string_literal: 'invalid'
it_behaves_like 'magic comment',
'# -*- encoding : ascii-8bit -*-',
encoding: 'ascii-8bit',
frozen_string_literal: nil
it_behaves_like 'magic comment',
'# encoding: ascii-8bit frozen_string_literal: true',
encoding: 'ascii-8bit',
frozen_string_literal: nil
it_behaves_like 'magic comment',
'# frozen_string_literal: true encoding: ascii-8bit',
encoding: 'ascii-8bit',
frozen_string_literal: nil
it_behaves_like 'magic comment',
' CSV.generate(encoding: Encoding::UTF_8) do |csv|',
encoding: nil,
frozen_string_literal: nil
it_behaves_like(
'magic comment',
'# -*- encoding: ASCII-8BIT; frozen_string_literal: true -*-',
encoding: 'ascii-8bit',
frozen_string_literal: true
)
it_behaves_like(
'magic comment',
'# coding: utf-8 -*- encoding: ASCII-8BIT; frozen_string_literal: true -*-',
encoding: 'ascii-8bit',
frozen_string_literal: true
)
it_behaves_like(
'magic comment',
'# -*- coding: ASCII-8BIT; typed: strict -*-',
encoding: 'ascii-8bit'
)
it_behaves_like 'magic comment',
'# vim: filetype=ruby, fileencoding=ascii-8bit',
encoding: 'ascii-8bit'
it_behaves_like 'magic comment', '# vim: filetype=ruby,fileencoding=ascii-8bit', encoding: nil
it_behaves_like 'magic comment',
'# vim: filetype=ruby, fileencoding=ascii-8bit',
encoding: 'ascii-8bit'
it_behaves_like 'magic comment',
'#vim: filetype=ruby, fileencoding=ascii-8bit',
encoding: 'ascii-8bit'
it_behaves_like 'magic comment',
'#vim: filetype=ruby, fileencoding=ascii-8bit, typed=strict',
encoding: 'ascii-8bit'
it_behaves_like(
'magic comment',
'# coding: utf-8 vim: filetype=ruby, fileencoding=ascii-8bit',
encoding: 'utf-8'
)
it_behaves_like 'magic comment',
'# vim: filetype=python, fileencoding=ascii-8bit',
encoding: 'ascii-8bit'
it_behaves_like 'magic comment', '# vim:fileencoding=utf-8', encoding: nil
describe '#valid?' do
subject { described_class.parse(comment).valid? }
context 'with an empty string' do
let(:comment) { '' }
it { is_expected.to be(false) }
end
context 'with a non magic comment' do
let(:comment) { '# do something' }
it { is_expected.to be(false) }
end
context 'with an encoding comment' do
let(:comment) { '# encoding: utf-8' }
it { is_expected.to be(true) }
end
context 'with a frozen string literal comment' do
let(:comment) { '# frozen-string-literal: true' }
it { is_expected.to be(true) }
end
context 'with a shareable constant value comment' do
let(:comment) { '# shareable-constant-value: literal' }
it { is_expected.to be(true) }
end
end
describe '#valid_rbs_inline_value?' do
subject { described_class.parse(comment).valid_rbs_inline_value? }
context 'when given comment specified as `enabled`' do
let(:comment) { '# rbs_inline: enabled' }
it { is_expected.to be(true) }
end
context 'when given comment specified as `disabled`' do
let(:comment) { '# rbs_inline: disabled' }
it { is_expected.to be(true) }
end
context 'when given comment specified as an invalid value`' do
let(:comment) { '# rbs_inline: invalid' }
it { is_expected.to be(false) }
end
end
describe '#valid_shareable_constant_value?' do
subject { described_class.parse(comment).valid_shareable_constant_value? }
context 'when given comment specified as `none`' do
let(:comment) { '# shareable_constant_value: none' }
it { is_expected.to be(true) }
end
context 'when given comment specified as `literal`' do
let(:comment) { '# shareable_constant_value: literal' }
it { is_expected.to be(true) }
end
context 'when given comment specified as `experimental_everything`' do
let(:comment) { '# shareable_constant_value: experimental_everything' }
it { is_expected.to be(true) }
end
context 'when given comment specified as `experimental_copy`' do
let(:comment) { '# shareable_constant_value: experimental_copy' }
it { is_expected.to be(true) }
end
context 'when given comment specified as unknown value' do
let(:comment) { '# shareable_constant_value: unknown' }
it { is_expected.to be(false) }
end
context 'when given comment is not specified' do
let(:comment) { '' }
it { is_expected.to be(false) }
end
end
describe '#without' do
subject { described_class.parse(comment).without(:encoding) }
context 'simple format' do
context 'when the entire comment is a single value' do
let(:comment) { '# encoding: utf-8' }
it { is_expected.to eq('') }
end
context 'when the comment contains a different magic value' do
let(:comment) { '# frozen-string-literal: true' }
it { is_expected.to eq(comment) }
end
end
context 'emacs format' do
context 'with one token' do
let(:comment) { '# -*- coding: ASCII-8BIT -*-' }
it { is_expected.to eq('') }
end
context 'with multiple tokens' do
let(:comment) { '# -*- coding: ASCII-8BIT; frozen_string_literal: true -*-' }
it { is_expected.to eq('# -*- frozen_string_literal: true -*-') }
end
end
context 'vim format' do
context 'when the comment has multiple tokens' do
let(:comment) { '# vim: filetype=ruby, fileencoding=ascii-8bit' }
it { is_expected.to eq('# vim: filetype=ruby') }
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/yaml_duplication_checker_spec.rb | spec/rubocop/yaml_duplication_checker_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::YAMLDuplicationChecker do
def check(yaml, &block)
described_class.check(yaml, 'dummy.yaml', &block)
end
shared_examples 'call block' do
it 'calls block' do
called = false
check(yaml) { called = true }
expect(called).to be(true)
end
end
context 'when yaml has duplicated keys in the top level' do
let(:yaml) { <<~YAML }
Layout/IndentationStyle:
Enabled: true
Layout/IndentationStyle:
Enabled: false
YAML
it_behaves_like 'call block'
it 'calls block with keys' do
key1 = nil
key2 = nil
check(yaml) do |key_a, key_b|
key1 = key_a
key2 = key_b
end
expect(key1.start_line).to eq(0)
expect(key2.start_line).to eq(3)
expect(key1.value).to eq('Layout/IndentationStyle')
expect(key2.value).to eq('Layout/IndentationStyle')
end
end
context 'when yaml has duplicated keys in the second level' do
let(:yaml) { <<~YAML }
Layout/IndentationStyle:
Enabled: true
Enabled: false
YAML
it_behaves_like 'call block'
it 'calls block with keys' do
key1 = nil
key2 = nil
check(yaml) do |key_a, key_b|
key1 = key_a
key2 = key_b
end
expect(key1.start_line).to eq(1)
expect(key2.start_line).to eq(2)
expect(key1.value).to eq('Enabled')
expect(key2.value).to eq('Enabled')
end
end
context 'when yaml does not have any duplication' do
let(:yaml) { <<~YAML }
Style/TrailingCommaInHashLiteral:
Enabled: true
EnforcedStyleForMultiline: no_comma
Style/TrailingBodyOnModule:
Enabled: true
YAML
it 'does not call block' do
called = false
described_class.check(yaml, 'dummy.yaml') { called = true }
expect(called).to be(false)
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/target_ruby_spec.rb | spec/rubocop/target_ruby_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::TargetRuby, :isolated_environment do
include FileHelper
subject(:target_ruby) { described_class.new(configuration) }
let(:configuration) { RuboCop::Config.new(hash, loaded_path) }
let(:default_version) { described_class::DEFAULT_VERSION }
let(:hash) { {} }
let(:loaded_path) { 'example/.rubocop.yml' }
context 'when TargetRubyVersion is set' do
let(:ruby_version) { 2.5 }
let(:hash) { { 'AllCops' => { 'TargetRubyVersion' => ruby_version } } }
it 'uses TargetRubyVersion' do
expect(target_ruby.version).to eq ruby_version
end
it 'does not read .ruby-version' do
expect(File).not_to receive(:file?).with('.ruby-version')
expect(target_ruby.version).to eq 2.5
end
it 'does not read Gemfile.lock or gems.locked' do
expect(File).not_to receive(:file?).with('Gemfile')
expect(File).not_to receive(:file?).with('gems.locked')
expect(target_ruby.version).to eq 2.5
end
end
context 'when RUBOCOP_TARGET_RUBY_VERSION is set' do
it 'uses RUBOCOP_TARGET_RUBY_VERSION' do
old_version = ENV.fetch('RUBOCOP_TARGET_RUBY_VERSION', nil)
begin
ENV['RUBOCOP_TARGET_RUBY_VERSION'] = '2.7'
expect(target_ruby.version).to eq 2.7
ensure
ENV['RUBOCOP_TARGET_RUBY_VERSION'] = old_version
end
end
it 'does not read .ruby-version' do
expect(File).not_to receive(:file?).with('.ruby-version')
old_version = ENV.fetch('RUBOCOP_TARGET_RUBY_VERSION', nil)
begin
ENV['RUBOCOP_TARGET_RUBY_VERSION'] = '2.7'
expect(target_ruby.version).to eq 2.7
ensure
ENV['RUBOCOP_TARGET_RUBY_VERSION'] = old_version
end
end
it 'does not read Gemfile.lock or gems.locked' do
expect(File).not_to receive(:file?).with('Gemfile')
expect(File).not_to receive(:file?).with('gems.locked')
old_version = ENV.fetch('RUBOCOP_TARGET_RUBY_VERSION', nil)
begin
ENV['RUBOCOP_TARGET_RUBY_VERSION'] = '2.7'
expect(target_ruby.version).to eq 2.7
ensure
ENV['RUBOCOP_TARGET_RUBY_VERSION'] = old_version
end
end
end
context 'when TargetRubyVersion is not set' do
context 'when gemspec file is present' do
let(:base_path) { configuration.base_dir_for_path_parameters }
let(:gemspec_file_path) { File.join(base_path, 'example.gemspec') }
context 'when file contains `required_ruby_version` as a string' do
it 'sets target_ruby from inclusive range' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = '>= 3.2.2'
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 3.2
end
it 'sets target_ruby from exclusive range' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = '> 3.2.2'
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 3.2
end
it 'sets target_ruby from approximate version' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = '~> 3.2.0'
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 3.2
end
end
context 'when file contains `required_ruby_version` as a requirement' do
it 'sets target_ruby from required_ruby_version from inclusive requirement range' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = Gem::Requirement.new('>= 2.3.1')
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 2.3
end
it 'falls back to the minimal supported analysable ruby version' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.required_ruby_version = '>= 1.9.0'
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 2.0
end
it 'sets first known ruby version that satisfies requirement' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = Gem::Requirement.new('< 3.0.0')
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 2.0
end
it 'sets first known ruby version that satisfies range requirement' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = Gem::Requirement.new('>= 2.3.1', '< 3.0.0')
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 2.3
end
it 'sets first known ruby version that satisfies range requirement in array notation' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = Gem::Requirement.new(['>= 2.3.1', '< 3.0.0'])
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 2.3
end
it 'sets first known ruby version that satisfies range requirement with frozen strings' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = Gem::Requirement.new('>= 2.3.1'.freeze, '< 3.0.0'.freeze)
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 2.3
end
it 'sets first known ruby version that satisfies range requirement in array notation with frozen strings' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = Gem::Requirement.new(['>= 2.3.1'.freeze, '< 3.0.0'.freeze])
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 2.3
end
end
context 'when file contains `required_ruby_version` as an array' do
it 'sets target_ruby to the minimal version satisfying the requirements' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = ['<=3.3.0', '>=3.1.3']
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 3.1
end
it 'sets target_ruby from required_ruby_version with many requirements' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = ['<=3.3.0', '>3.1.1', '~>3.2.1']
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 3.2
end
end
context 'when file reads the required_ruby_version from another file' do
it 'uses the default target ruby version' do
content = <<~'HEREDOC'
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = Gem::Requirement.new(">= #{File.read('.ruby-version').rstrip}")
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq default_version
end
end
context 'when file reads the required_ruby_version from another file in an array' do
it 'uses the default target ruby version' do
content = <<~'HEREDOC'
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = [">= #{File.read('.ruby-version').rstrip}"]
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq default_version
end
end
context 'when required_ruby_version sets the target ruby' do
before do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = '>= 2.7.2'
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
end
it 'does not check the other sources' do
expect(described_class::RubyVersionFile).not_to receive(:new)
expect(described_class::ToolVersionsFile).not_to receive(:new)
expect(described_class::BundlerLockFile).not_to receive(:new)
expect(described_class::Default).not_to receive(:new)
expect(target_ruby.version).to eq 2.7
end
end
context 'when parser_prism is configured' do
let(:hash) { { 'AllCops' => { 'ParserEngine' => 'parser_prism' } } }
it 'can parse gemspec file without error' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = '>= 3.3.0'
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 3.3
end
end
context 'when file does not contain `required_ruby_version`' do
before do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.platform = Gem::Platform::RUBY
s.licenses = ['MIT']
s.summary = 'test tool.'
end
HEREDOC
create_file(gemspec_file_path, content)
end
it 'checks the rest of the sources' do
expect(described_class::RubyVersionFile).to receive(:new).and_call_original
expect(described_class::ToolVersionsFile).to receive(:new).and_call_original
expect(described_class::BundlerLockFile).to receive(:new).and_call_original
expect(described_class::Default).to receive(:new).and_call_original
expect(target_ruby.version).to eq default_version
end
end
context 'when file contains a syntax error' do
it 'uses the default target ruby version' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.required_ruby_version = '>= 3.3.0'' # invalid syntax
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq default_version
end
end
context 'when the gemspec is not named the same as the directory' do
let(:gemspec_file_path) { File.join(base_path, 'whatever.gemspec') }
it 'sets target_ruby from the version' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = '~> 3.2.0'
s.licenses = ['MIT']
end
HEREDOC
create_file(gemspec_file_path, content)
expect(target_ruby.version).to eq 3.2
end
end
context 'when there are multiple gemspecs in the same directory' do
let(:first_gemspec_file_path) { File.join(base_path, 'first.gemspec') }
let(:second_gemspec_file_path) { File.join(base_path, 'second.gemspec') }
it 'takes neither' do
content = <<~HEREDOC
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = '~> 3.2.0'
s.licenses = ['MIT']
end
HEREDOC
create_file(first_gemspec_file_path, content)
create_file(second_gemspec_file_path, content)
expect(target_ruby.version).to eq default_version
end
end
end
context 'when .ruby-version is present' do
before do
dir = configuration.base_dir_for_path_parameters
create_file(File.join(dir, '.ruby-version'), ruby_version)
end
context 'when .ruby-version contains an MRI version' do
let(:ruby_version) { '2.4.10' }
let(:ruby_version_to_f) { 2.4 }
it 'reads it to determine the target ruby version' do
expect(target_ruby.version).to eq ruby_version_to_f
end
end
context 'when the MRI version contains multiple digits' do
let(:ruby_version) { '10.11.0' }
let(:ruby_version_to_f) { 10.11 }
it 'reads it to determine the target ruby version' do
expect(target_ruby.version).to eq ruby_version_to_f
end
end
context 'when .ruby-version contains a version prefixed by "ruby-"' do
let(:ruby_version) { 'ruby-2.4.0' }
let(:ruby_version_to_f) { 2.4 }
it 'correctly determines the target ruby version' do
expect(target_ruby.version).to eq ruby_version_to_f
end
end
context 'when .ruby-version contains a JRuby version' do
let(:ruby_version) { 'jruby-9.1.2.0' }
it 'uses the default target ruby version' do
expect(target_ruby.version).to eq default_version
end
end
context 'when .ruby-version contains a Rbx version' do
let(:ruby_version) { 'rbx-3.42' }
it 'uses the default target ruby version' do
expect(target_ruby.version).to eq default_version
end
end
context 'when .ruby-version contains "system" version' do
let(:ruby_version) { 'system' }
it 'uses the default target ruby version' do
expect(target_ruby.version).to eq default_version
end
end
it 'does not read .tool-versions, Gemfile.lock or gems.locked' do
expect(File).not_to receive(:file?).with('.tool-versions')
expect(File).not_to receive(:file?).with('Gemfile')
expect(File).not_to receive(:file?).with('gems.locked')
expect(target_ruby.version).to eq default_version
end
end
context 'when .tool-versions is present' do
before do
dir = configuration.base_dir_for_path_parameters
create_file(File.join(dir, '.tool-versions'), tool_versions)
end
context 'when .tool-versions does not contain a ruby version' do
let(:tool_versions) { ['nodejs 14.9.0'] }
it 'uses the default ruby version' do
expect(target_ruby.version).to eq default_version
end
end
context 'when .tool-versions contains only a ruby version' do
let(:tool_versions) { ['ruby 3.0.0'] }
let(:ruby_version_to_f) { 3.0 }
it 'reads it to determine the target ruby version' do
expect(target_ruby.version).to eq ruby_version_to_f
end
it 'does not read Gemfile.lock, gems.locked' do
expect(File).not_to receive(:file?).with(/Gemfile/)
expect(File).not_to receive(:file?).with(/gems\.locked/)
expect(target_ruby.version).to eq default_version
end
end
context 'when .tool-versions contains different runtimes' do
let(:tool_versions) { ['nodejs 14.9.0', 'ruby 3.0.0'] }
let(:ruby_version_to_f) { 3.0 }
it 'reads it to determine the target ruby version' do
expect(target_ruby.version).to eq ruby_version_to_f
end
it 'does not read Gemfile.lock, gems.locked' do
expect(File).not_to receive(:file?).with(/Gemfile/)
expect(File).not_to receive(:file?).with(/gems\.locked/)
expect(target_ruby.version).to eq default_version
end
end
end
context 'when .ruby-version is not present' do
['Gemfile.lock', 'gems.locked'].each do |file_name|
context "and #{file_name} exists" do
let(:base_path) { configuration.base_dir_for_path_parameters }
let(:lock_file_path) { File.join(base_path, file_name) }
it "uses MRI Ruby version when it is present in #{file_name}" do
content = <<~HEREDOC
GEM
remote: https://rubygems.org/
specs:
actionmailer (4.1.0)
actionpack (= 4.1.0)
rails (4.1.0)
actionmailer (= 4.1.0)
actionpack (= 4.1.0)
railties (= 4.1.0)
railties (4.1.0)
PLATFORMS
ruby
DEPENDENCIES
ruby-extensions (~> 1.9.0)
RUBY VERSION
ruby 2.0.0p0
BUNDLED WITH
1.16.1
HEREDOC
create_file(lock_file_path, content)
expect(target_ruby.version).to eq 2.0
end
it 'uses MRI Ruby version when it has multiple digits' do
content = <<~HEREDOC
GEM
remote: https://rubygems.org/
specs:
actionmailer (4.1.0)
actionpack (= 4.1.0)
rails (4.1.0)
actionmailer (= 4.1.0)
actionpack (= 4.1.0)
railties (= 4.1.0)
railties (4.1.0)
PLATFORMS
ruby
DEPENDENCIES
ruby-extensions (~> 1.9.0)
RUBY VERSION
ruby 20.10.100p450
BUNDLED WITH
1.16.1
HEREDOC
create_file(lock_file_path, content)
expect(target_ruby.version).to eq 20.10
end
it "uses the default Ruby when Ruby is not in #{file_name}" do
content = <<~HEREDOC
GEM
remote: https://rubygems.org/
specs:
addressable (2.5.2)
public_suffix (>= 2.0.2, < 4.0)
ast (2.4.0)
bump (0.5.4)
PLATFORMS
ruby
DEPENDENCIES
bump
bundler (~> 1.3)
ruby-extensions (~> 1.9.0)
BUNDLED WITH
1.16.1
HEREDOC
create_file(lock_file_path, content)
expect(target_ruby.version).to eq default_version
end
it "uses the default Ruby when rbx is in #{file_name}" do
content = <<~HEREDOC
GEM
remote: https://rubygems.org/
specs:
addressable (2.5.2)
public_suffix (>= 2.0.2, < 4.0)
ast (2.4.0)
bump (0.5.4)
PLATFORMS
ruby
DEPENDENCIES
bump
bundler (~> 1.3)
ruby-extensions (~> 1.9.0)
RUBY VERSION
ruby 2.0.0p0 (rbx 3.42)
BUNDLED WITH
1.16.1
HEREDOC
create_file(lock_file_path, content)
expect(target_ruby.version).to eq default_version
end
it "uses the default Ruby when jruby is in #{file_name}" do
content = <<~HEREDOC
GEM
remote: https://rubygems.org/
specs:
addressable (2.5.2)
public_suffix (>= 2.0.2, < 4.0)
ast (2.4.0)
bump (0.5.4)
PLATFORMS
ruby
DEPENDENCIES
bump
bundler (~> 1.3)
ruby-extensions (~> 1.9.0)
RUBY VERSION
ruby 2.0.0p0 (jruby 9.1.13.0)
BUNDLED WITH
1.16.1
HEREDOC
create_file(lock_file_path, content)
expect(target_ruby.version).to eq default_version
end
end
end
context 'when bundler lock files are not present' do
it 'uses the default target ruby version' do
expect(target_ruby.version).to eq default_version
end
end
end
context 'when .ruby-version is in a parent directory' do
before do
dir = configuration.base_dir_for_path_parameters
create_file(File.join(dir, '..', '.ruby-version'), '2.5.8')
end
it 'reads it to determine the target ruby version' do
expect(target_ruby.version).to eq 2.5
end
end
context 'when .ruby-version is not in a parent directory' do
['Gemfile.lock', 'gems.locked'].each do |file_name|
context "when #{file_name} is in a parent directory" do
it 'does' do
content = <<~HEREDOC
GEM
remote: https://rubygems.org/
specs:
actionmailer (4.1.0)
actionpack (= 4.1.0)
rails (4.1.0)
actionmailer (= 4.1.0)
actionpack (= 4.1.0)
railties (= 4.1.0)
railties (4.1.0)
PLATFORMS
ruby
DEPENDENCIES
ruby-extensions (~> 1.9.0)
RUBY VERSION
ruby 2.0.0p0
BUNDLED WITH
1.16.1
HEREDOC
dir = configuration.base_dir_for_path_parameters
create_file(File.join(dir, '..', file_name), content)
expect(target_ruby.version).to eq 2.0
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/target_finder_spec.rb | spec/rubocop/target_finder_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::TargetFinder, :isolated_environment do
include FileHelper
ruby_extensions = %w[.rb
.arb
.axlsx
.builder
.fcgi
.gemfile
.gemspec
.god
.jb
.jbuilder
.mspec
.opal
.pluginspec
.podspec
.rabl
.rake
.rbuild
.rbw
.rbx
.ru
.ruby
.schema
.spec
.thor
.watchr]
ruby_interpreters = %w[ruby macruby rake jruby rbx]
ruby_filenames = %w[.irbrc
.pryrc
.simplecov
Appraisals
Berksfile
Brewfile
Buildfile
Capfile
Cheffile
Dangerfile
Deliverfile
Fastfile
Gemfile
Guardfile
Jarfile
Mavenfile
Podfile
Puppetfile
Rakefile
rakefile
Schemafile
Snapfile
Steepfile
Thorfile
Vagabondfile
Vagrantfile
buildfile]
subject(:target_finder) { described_class.new(config_store, options) }
let(:config_store) { RuboCop::ConfigStore.new }
let(:options) do
{
force_exclusion: force_exclusion,
ignore_parent_exclusion: ignore_parent_exclusion,
debug: debug
}
end
let(:force_exclusion) { false }
let(:ignore_parent_exclusion) { false }
let(:debug) { false }
before do
create_empty_file('dir1/ruby1.rb')
create_empty_file('dir1/ruby2.rb')
create_empty_file('dir1/file.txt')
create_empty_file('dir1/file')
create_file('dir1/executable', '#!/usr/bin/env ruby')
create_empty_file('dir2/ruby3.rb')
create_empty_file('.hidden/ruby4.rb')
RuboCop::ConfigLoader.clear_options
end
shared_examples 'common behavior for #find' do
context 'when a file with a ruby filename is passed' do
let(:args) { ruby_filenames.map { |name| "dir2/#{name}" } }
it 'picks all the ruby files' do
expect(found_basenames).to eq(ruby_filenames)
end
end
context 'when files with ruby interpreters are passed' do
let(:args) { ruby_interpreters.map { |name| "dir2/#{name}" } }
before do
ruby_interpreters.each do |interpreter|
create_file("dir2/#{interpreter}", "#!/usr/bin/#{interpreter}")
end
end
it 'picks all the ruby files' do
expect(found_basenames).to eq(ruby_interpreters)
end
end
context 'when a pattern is passed' do
let(:args) { ['dir1/*2.rb'] }
it 'finds files which match the pattern' do
expect(found_basenames).to eq(['ruby2.rb'])
end
end
context 'when a pattern with matching folders is passed' do
before { create_empty_file('app/dir.rb/ruby.rb') }
let(:args) { ['app/**/*.rb'] }
it 'finds only files which match the pattern' do
expect(found_basenames).to eq(['ruby.rb'])
end
end
context 'when same paths are passed' do
let(:args) { %w[dir1 dir1] }
it 'does not return duplicated file paths' do
count = found_basenames.count { |f| f == 'ruby1.rb' }
expect(count).to eq(1)
end
end
context 'when some paths are specified in the configuration Exclude ' \
'and they are explicitly passed as arguments' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
Exclude:
- dir1/ruby1.rb
- 'dir2/*'
YAML
create_file('dir1/.rubocop.yml', <<~YAML)
AllCops:
Exclude:
- executable
YAML
end
let(:args) { ['dir1/ruby1.rb', 'dir1/ruby2.rb', 'dir1/exe*', 'dir2/ruby3.rb'] }
context 'normally' do
it 'does not exclude them' do
expect(found_basenames).to eq(['ruby1.rb', 'ruby2.rb', 'executable', 'ruby3.rb'])
end
end
context "when it's forced to adhere file exclusion configuration" do
let(:force_exclusion) { true }
context 'when parent exclusion is in effect' do
before do
create_file('dir2/.rubocop.yml', <<~YAML)
require:
- unloadable_extension
YAML
end
it 'excludes only files that are excluded on top level and does not load ' \
'other configuration files unnecessarily' do
expect(found_basenames).to eq(['ruby2.rb', 'executable'])
end
end
context 'when parent exclusion is ignored' do
let(:ignore_parent_exclusion) { true }
it 'excludes files that are excluded on any level' do
expect(found_basenames).to eq(['ruby2.rb'])
end
end
end
end
it 'returns absolute paths' do
expect(found_files).not_to be_empty
found_files.each { |file| expect(Pathname.new(file)).to be_absolute }
end
it 'does not find hidden files' do
expect(found_files).not_to include('.hidden/ruby4.rb')
end
context 'when no argument is passed' do
let(:args) { [] }
it 'finds files under the current directory' do
Dir.chdir('dir1') do
expect(found_files).not_to be_empty
found_files.each do |file|
expect(file).to include('/dir1/')
expect(file).not_to include('/dir2/')
end
end
end
end
context 'when a directory path is passed' do
let(:args) { ['../dir2'] }
it 'finds files under the specified directory' do
Dir.chdir('dir1') do
expect(found_files).not_to be_empty
found_files.each do |file|
expect(file).to include('/dir2/')
expect(file).not_to include('/dir1/')
end
end
end
end
context 'when a hidden directory path is passed' do
let(:args) { ['.hidden'] }
it 'finds files under the specified directory' do
expect(found_files.size).to be(1)
expect(found_files.first).to include('.hidden/ruby4.rb')
end
end
context 'when some non-known Ruby files are specified in the ' \
'configuration Include and they are explicitly passed ' \
'as arguments' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
Include:
- dir1/file
YAML
end
let(:args) { ['dir1/file'] }
it 'includes them' do
expect(found_basenames).to contain_exactly('file')
end
end
end
shared_examples 'when input is passed on stdin' do
context 'when input is passed on stdin' do
let(:options) do
{
force_exclusion: force_exclusion,
debug: debug,
stdin: 'def example; end'
}
end
let(:args) { ['Untitled'] }
it 'includes the file' do
expect(found_basenames).to eq(['Untitled'])
end
end
end
describe '#find(..., :only_recognized_file_types)' do
let(:found_files) { target_finder.find(args, :only_recognized_file_types) }
let(:found_basenames) { found_files.map { |f| File.basename(f) } }
let(:args) { [] }
context 'when a hidden directory path is passed' do
let(:args) { ['.hidden'] }
it 'finds files under the specified directory' do
expect(found_files.size).to be(1)
expect(found_files.first).to include('.hidden/ruby4.rb')
end
end
context 'when a non-ruby file is passed' do
let(:args) { ['dir2/file'] }
it "doesn't pick the file" do
expect(found_basenames).to be_empty
end
end
context 'when files with a ruby extension are passed' do
let(:args) { ruby_extensions.map { |ext| "dir2/file#{ext}" } }
it 'picks all the ruby files' do
expect(found_basenames).to eq(ruby_extensions.map { |ext| "file#{ext}" })
end
context 'when local AllCops/Include lists two patterns' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
Include:
- '**/*.rb'
- '**/*.arb'
YAML
end
it 'picks two files' do
expect(found_basenames).to eq(%w[file.rb file.arb])
end
context 'when a subdirectory AllCops/Include only lists one pattern' do
before do
create_file('dir2/.rubocop.yml', <<~YAML)
AllCops:
Include:
- '**/*.ruby'
YAML
end
# Include and Exclude patterns are take from the top directory and
# settings in subdirectories are silently ignored.
it 'picks two files' do
expect(found_basenames).to eq(%w[file.rb file.arb])
end
end
end
end
it_behaves_like 'common behavior for #find'
context 'when some non-known Ruby files are specified in the ' \
'configuration Include and they are not explicitly passed ' \
'as arguments' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
Include:
- '**/*.rb'
- dir1/file
YAML
end
let(:args) { ['dir1/**/*'] }
it 'includes them' do
expect(found_basenames).to contain_exactly('executable', 'file', 'ruby1.rb', 'ruby2.rb')
end
end
it_behaves_like 'when input is passed on stdin'
end
describe '#find(..., :all_file_types)' do
let(:found_files) { target_finder.find(args, :all_file_types) }
let(:found_basenames) { found_files.map { |f| File.basename(f) } }
let(:args) { [] }
it_behaves_like 'common behavior for #find'
context 'when a non-ruby file is passed' do
let(:args) { ['dir2/file'] }
it 'picks the file' do
expect(found_basenames).to contain_exactly('file')
end
end
context 'when files with a ruby extension are passed' do
shared_examples 'picks all the ruby files' do
it 'picks all the ruby files' do
expect(found_basenames).to eq(ruby_extensions.map { |ext| "file#{ext}" })
end
end
let(:args) { ruby_extensions.map { |ext| "dir2/file#{ext}" } }
it_behaves_like 'picks all the ruby files'
context 'when local AllCops/Include lists two patterns' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
Include:
- '**/*.rb'
- '**/*.arb'
YAML
end
it_behaves_like 'picks all the ruby files'
context 'when a subdirectory AllCops/Include only lists one pattern' do
before do
create_file('dir2/.rubocop.yml', <<~YAML)
AllCops:
Include:
- '**/*.ruby'
YAML
end
it_behaves_like 'picks all the ruby files'
end
end
end
context 'when some non-known Ruby files are specified in the ' \
'configuration Include and they are not explicitly passed ' \
'as arguments' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
Include:
- '**/*.rb'
- dir1/file
YAML
end
let(:args) { ['dir1/**/*'] }
it 'includes them' do
expect(found_basenames).to contain_exactly('executable', 'file',
'file.txt', 'ruby1.rb',
'ruby2.rb')
end
end
it_behaves_like 'when input is passed on stdin'
end
describe '#find_files' do
let(:found_files) { target_finder.find_files(base_dir, flags) }
let(:found_basenames) { found_files.map { |f| File.basename(f) } }
let(:base_dir) { Dir.pwd }
let(:flags) { 0 }
it 'does not search excluded top level directories' do
config = instance_double(RuboCop::Config)
exclude_property = { 'Exclude' => [File.expand_path('dir1/**/*')] }
allow(config).to receive(:for_all_cops).and_return(exclude_property)
allow(config_store).to receive(:for).and_return(config)
expect(found_basenames).not_to include('ruby1.rb')
expect(found_basenames).to include('ruby3.rb')
end
it 'works also if a folder is named ","' do
create_empty_file(',/ruby4.rb')
config = instance_double(RuboCop::Config)
exclude_property = { 'Exclude' => [File.expand_path('dir1/**/*')] }
allow(config).to receive(:for_all_cops).and_return(exclude_property)
allow(config_store).to receive(:for).and_return(config)
expect(found_basenames).not_to include('ruby1.rb')
expect(found_basenames).to include('ruby3.rb')
expect(found_basenames).to include('ruby4.rb')
end
it 'works also if a folder is named "{}"' do
create_empty_file('{}/ruby4.rb')
config = instance_double(RuboCop::Config)
exclude_property = { 'Exclude' => [File.expand_path('dir1/**/*')] }
allow(config).to receive(:for_all_cops).and_return(exclude_property)
allow(config_store).to receive(:for).and_return(config)
expect(found_basenames).not_to include('ruby1.rb')
expect(found_basenames).to include('ruby3.rb')
expect(found_basenames).to include('ruby4.rb')
end
it 'works also if a folder is named "{foo}"' do
create_empty_file('{foo}/ruby4.rb')
config = instance_double(RuboCop::Config)
exclude_property = { 'Exclude' => [File.expand_path('dir1/**/*')] }
allow(config).to receive(:for_all_cops).and_return(exclude_property)
allow(config_store).to receive(:for).and_return(config)
expect(found_basenames).not_to include('ruby1.rb')
expect(found_basenames).to include('ruby3.rb')
expect(found_basenames).to include('ruby4.rb')
end
it 'works also if a folder is named "[...something]"' do
create_empty_file('[...something]/ruby4.rb')
config = instance_double(RuboCop::Config)
exclude_property = { 'Exclude' => [File.expand_path('dir1/**/*')] }
allow(config).to receive(:for_all_cops).and_return(exclude_property)
allow(config_store).to receive(:for).and_return(config)
expect(found_basenames).not_to include('ruby1.rb')
expect(found_basenames).to include('ruby3.rb')
expect(found_basenames).to include('ruby4.rb')
end
it 'works if patterns are empty' do
allow(Dir).to receive(:glob).and_call_original
allow_any_instance_of(described_class).to receive(:wanted_dir_patterns).and_return([])
expect(Dir).to receive(:glob).with([File.join(base_dir, '**/*')], flags)
expect(found_basenames).to include(
'executable',
'file.txt',
'file',
'ruby1.rb',
'ruby2.rb',
'ruby3.rb'
)
end
# Cannot create a directory with containing `*` character on Windows.
# https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
unless RuboCop::Platform.windows?
it 'works also if a folder is named "**"' do
create_empty_file('**/ruby5.rb')
config = instance_double(RuboCop::Config)
exclude_property = { 'Exclude' => [File.expand_path('dir1/**/*')] }
allow(config).to receive(:for_all_cops).and_return(exclude_property)
allow(config_store).to receive(:for).and_return(config)
expect(found_basenames).to include('ruby5.rb')
end
end
it 'prevents infinite loops when traversing symlinks' do
create_link('dir1/link/', File.expand_path('dir1'))
expect(found_basenames).to include('ruby1.rb').once
end
it 'resolves symlinks when looking for excluded directories' do
create_link('link', 'dir1')
config = instance_double(RuboCop::Config)
exclude_property = { 'Exclude' => [File.expand_path('dir1/**/*')] }
allow(config).to receive(:for_all_cops).and_return(exclude_property)
allow(config_store).to receive(:for).and_return(config)
expect(found_basenames).not_to include('ruby1.rb')
expect(found_basenames).to include('ruby3.rb')
end
it 'can exclude symlinks as well as directories' do
create_empty_file(File.join(Dir.home, 'ruby5.rb'))
create_link('link', Dir.home)
config = instance_double(RuboCop::Config)
exclude_property = { 'Exclude' => [File.expand_path('link/**/*')] }
allow(config).to receive(:for_all_cops).and_return(exclude_property)
allow(config_store).to receive(:for).and_return(config)
expect(found_basenames).not_to include('ruby5.rb')
expect(found_basenames).to include('ruby3.rb')
end
end
describe '#target_files_in_dir' do
let(:found_files) { target_finder.target_files_in_dir(base_dir) }
let(:found_basenames) { found_files.map { |f| File.basename(f) } }
let(:base_dir) { '.' }
it 'picks files with extension .rb' do
rb_file_count = found_files.count { |f| f.end_with?('.rb') }
expect(rb_file_count).to eq(3)
end
it 'picks ruby executable files with no extension' do
expect(found_basenames).to include('executable')
end
it 'does not pick files with no extension and no ruby shebang' do
expect(found_basenames).not_to include('file')
end
it 'does not pick directories' do
found_basenames = found_files.map { |f| File.basename(f) }
allow(config_store).to receive(:for).and_return({})
expect(found_basenames).not_to include('dir1')
end
it 'picks files specified to be included in config' do
config = instance_double(RuboCop::Config)
allow(config).to receive(:file_to_include?) do |file|
File.basename(file) == 'file'
end
allow(config).to receive_messages(
for_all_cops: { 'Exclude' => [], 'Include' => [], 'RubyInterpreters' => [] },
:[] => [],
file_to_exclude?: false
)
allow(config_store).to receive(:for).and_return(config)
expect(found_basenames).to include('file')
end
it 'does not pick files specified to be excluded in config' do
config = instance_double(RuboCop::Config).as_null_object
allow(config).to receive_messages(
for_all_cops: { 'Exclude' => [], 'Include' => [], 'RubyInterpreters' => [] },
file_to_include?: false
)
allow(config).to receive(:file_to_exclude?) do |file|
File.basename(file) == 'ruby2.rb'
end
allow(config_store).to receive(:for).and_return(config)
expect(found_basenames).not_to include('ruby2.rb')
end
context 'when an exception is raised while reading file' do
include_context 'mock console output'
before { allow_any_instance_of(File).to receive(:readline).and_raise(EOFError) }
context 'and debug mode is enabled' do
let(:debug) { true }
it 'outputs error message' do
found_files
expect($stderr.string).to include('Unprocessable file')
end
end
context 'and debug mode is disabled' do
let(:debug) { false }
it 'outputs nothing' do
found_files
expect($stderr.string).to be_empty
end
end
end
context 'when file is zero-sized' do
include_context 'mock console output'
before do
create_file('dir1/flag', nil)
end
context 'and debug mode is enabled' do
let(:debug) { true }
it 'outputs error message' do
found_files
expect($stderr.string).to be_empty
end
end
context 'and debug mode is disabled' do
let(:debug) { false }
it 'outputs nothing' do
found_files
expect($stderr.string).to be_empty
end
end
end
context 'when provided directory contains hidden segments' do
let(:base_dir) { File.expand_path('.hidden') }
it 'picks relevant files within provided directory' do
expect(found_basenames).to match_array(%w[ruby4.rb])
end
context 'with nested hidden directory' do
before do
create_empty_file('.hidden/.nested-hidden/ruby5.rb')
create_file('.hidden/shebang-ruby', '#! /usr/bin/env ruby')
create_file('.hidden/shebang-zsh', '#! /usr/bin/env zsh')
end
it 'picks relevant files within provided directory' do
expect(found_basenames).to match_array(%w[ruby4.rb ruby5.rb shebang-ruby])
end
end
end
context 'w/ --fail-fast option' do
let(:options) { { force_exclusion: force_exclusion, debug: debug, fail_fast: true } }
it 'works with the expected number of .rb files' do
rb_file_count = found_files.count { |f| f.end_with?('.rb') }
expect(rb_file_count).to eq(3)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/feature_loader_spec.rb | spec/rubocop/feature_loader_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::FeatureLoader do
describe '.load' do
subject(:load) do
described_class.load(config_directory_path: config_directory_path, feature: feature)
end
let(:config_directory_path) do
'path-to-config'
end
let(:feature) do
'feature'
end
let(:allow_feature_loader) do
allow_any_instance_of(described_class) # rubocop:disable RSpec/AnyInstance
end
let(:expect_feature_loader) do
expect_any_instance_of(described_class) # rubocop:disable RSpec/AnyInstance, RSpec/ExpectInLet
end
context 'with normally loadable feature' do
before do
allow_feature_loader.to receive(:require)
end
it 'loads it normally' do
expect_feature_loader.to receive(:require).with('feature')
load
end
end
context 'with dot-prefixed loadable feature' do
before do
allow_feature_loader.to receive(:require)
end
let(:feature) do
'./path/to/feature'
end
it 'loads it as relative path' do
expect_feature_loader.to receive(:require).with('path-to-config/./path/to/feature')
load
end
end
context 'with namespaced feature' do
before do
allow_feature_loader.to receive(:require).with('feature-foo').and_call_original
allow_feature_loader.to receive(:require).with('feature/foo')
end
let(:feature) do
'feature-foo'
end
it 'loads it as namespaced feature' do
expect_feature_loader.to receive(:require).with('feature/foo')
load
end
end
context 'with dot-prefixed namespaced feature' do
before do
allow_feature_loader.to receive(:require).with('path-to-config/./feature-foo')
.and_call_original
allow_feature_loader.to receive(:require).with('path-to-config/./feature/foo')
end
let(:feature) do
'./feature-foo'
end
it 'loads it as namespaced feature' do
expect_feature_loader.to receive(:require).with('path-to-config/./feature/foo')
load
end
end
context 'with unexpected LoadError from require' do
before do
allow_feature_loader.to receive(:require).and_raise(LoadError)
end
it 'raises LoadError' do
expect { load }.to raise_error(LoadError)
end
end
context 'with unloadable namespaced feature' do
let(:feature) do
'feature-foo'
end
# In normal Ruby, the message starts with "cannot load such file",
# but in JRuby it seems to start with "no such file to load".
it 'raises LoadError with preferred message' do
expect { load }.to raise_error(LoadError, /feature-foo/)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/pending_cops_reporter_spec.rb | spec/rubocop/pending_cops_reporter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::PendingCopsReporter do
include FileHelper
describe 'when pending cops exist', :isolated_environment do
subject(:report_pending_cops) { described_class.warn_if_needed(config) }
let(:config) { RuboCop::Config.new(parent_config) }
before do
create_empty_file('.rubocop.yml')
# Setup similar to https://github.com/rubocop/rubocop-rspec/blob/master/lib/rubocop/rspec/inject.rb#L16
# and https://github.com/runtastic/rt_rubocop_defaults/blob/master/lib/rt_rubocop_defaults/inject.rb#L21
loader = RuboCop::ConfigLoader.configuration_from_file('.rubocop.yml')
loader.instance_variable_set(:@default_configuration, config)
end
context 'when NewCops is set in a required file' do
let(:parent_config) { { 'AllCops' => { 'NewCops' => 'enable' } } }
it 'does not print a warning' do
expect(described_class).not_to receive(:warn_on_pending_cops)
report_pending_cops
end
end
context 'when NewCops is not configured in a required file' do
let(:parent_config) { { 'AllCops' => { 'Exclude:' => ['coverage/**/*'] } } }
context 'when `pending_cops_only_qualified` returns empty array' do
before do
allow(described_class).to receive(:pending_cops_only_qualified).and_return([])
end
it 'does not print a warning' do
expect(described_class).not_to receive(:warn_on_pending_cops)
report_pending_cops
end
end
context 'when `pending_cops_only_qualified` returns not empty array' do
before do
allow(described_class).to receive(:pending_cops_only_qualified).and_return(['Foo/Bar'])
end
it 'prints a warning' do
expect(described_class).to receive(:warn_on_pending_cops)
report_pending_cops
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/config_obsoletion_spec.rb | spec/rubocop/config_obsoletion_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::ConfigObsoletion do
include FileHelper
subject(:config_obsoletion) { described_class.new(configuration) }
let(:configuration) { RuboCop::Config.new(hash, loaded_path) }
let(:loaded_path) { 'example/.rubocop.yml' }
let(:plugins) { [] }
let(:requires) { [] }
before do
allow(configuration).to receive_messages(loaded_plugins: plugins, loaded_features: requires)
described_class.files = [described_class::DEFAULT_RULES_FILE]
end
after { described_class.files = [described_class::DEFAULT_RULES_FILE] }
describe '#validate', :isolated_environment do
context 'when the configuration includes any obsolete cop name' do
let(:hash) do
{
# Renamed cops
'Layout/AlignArguments' => { Enabled: true },
'Layout/AlignArray' => { Enabled: true },
'Layout/AlignHash' => { Enabled: true },
'Layout/AlignParameters' => { Enabled: true },
'Layout/FirstParameterIndentation' => { Enabled: true },
'Layout/IndentArray' => { Enabled: true },
'Layout/IndentAssignment' => { Enabled: true },
'Layout/IndentFirstArgument' => { Enabled: true },
'Layout/IndentFirstArrayElement' => { Enabled: true },
'Layout/IndentFirstHashElement' => { Enabled: true },
'Layout/IndentFirstParameter' => { Enabled: true },
'Layout/IndentHash' => { Enabled: true },
'Layout/IndentHeredoc' => { Enabled: true },
'Layout/LeadingBlankLines' => { Enabled: true },
'Layout/Tab' => { Enabled: true },
'Layout/TrailingBlankLines' => { Enabled: true },
'Lint/DuplicatedKey' => { Enabled: true },
'Lint/HandleExceptions' => { Enabled: true },
'Lint/MultipleCompare' => { Enabled: true },
'Lint/StringConversionInInterpolation' => { Enabled: true },
'Lint/UnneededCopDisableDirective' => { Enabled: true },
'Lint/UnneededCopEnableDirective' => { Enabled: true },
'Lint/UnneededRequireStatement' => { Enabled: true },
'Lint/UnneededSplatExpansion' => { Enabled: true },
'Naming/UncommunicativeBlockParamName' => { Enabled: true },
'Naming/UncommunicativeMethodParamName' => { Enabled: true },
'Style/DeprecatedHashMethods' => { Enabled: true },
'Style/MethodCallParentheses' => { Enabled: true },
'Style/OpMethod' => { Enabled: true },
'Style/SingleSpaceBeforeFirstArg' => { Enabled: true },
'Style/UnneededCapitalW' => { Enabled: true },
'Style/UnneededCondition' => { Enabled: true },
'Style/UnneededInterpolation' => { Enabled: true },
'Style/UnneededPercentQ' => { Enabled: true },
'Style/UnneededSort' => { Enabled: true },
# Moved cops
'Lint/BlockAlignment' => { Enabled: true },
'Lint/DefEndAlignment' => { Enabled: true },
'Lint/EndAlignment' => { Enabled: true },
'Lint/Eval' => { Enabled: true },
'Style/AccessorMethodName' => { Enabled: true },
'Style/AsciiIdentifiers' => { Enabled: true },
'Style/ClassAndModuleCamelCase' => { Enabled: true },
'Style/ConstantName' => { Enabled: true },
'Style/FileName' => { Enabled: true },
'Style/FlipFlop' => { Enabled: true },
'Style/MethodName' => { Enabled: true },
'Style/PredicateName' => { Enabled: true },
'Style/VariableName' => { Enabled: true },
'Style/VariableNumber' => { Enabled: true },
# Removed cops
'Layout/SpaceAfterControlKeyword' => { Enabled: true },
'Layout/SpaceBeforeModifierKeyword' => { Enabled: true },
'Lint/InvalidCharacterLiteral' => { Enabled: true },
'Style/MethodMissingSuper' => { Enabled: true },
'Lint/UselessComparison' => { Enabled: true },
'Lint/RescueWithoutErrorClass' => { Enabled: true },
'Lint/SpaceBeforeFirstArg' => { Enabled: true },
'Style/SpaceAfterControlKeyword' => { Enabled: true },
'Style/SpaceBeforeModifierKeyword' => { Enabled: true },
'Style/TrailingComma' => { Enabled: true },
'Style/TrailingCommaInLiteral' => { Enabled: true },
# Split cops
'Style/MethodMissing' => { Enabled: true }
}
end
let(:expected_message) do
<<~OUTPUT.chomp
The `Layout/AlignArguments` cop has been renamed to `Layout/ArgumentAlignment`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/AlignArray` cop has been renamed to `Layout/ArrayAlignment`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/AlignHash` cop has been renamed to `Layout/HashAlignment`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/AlignParameters` cop has been renamed to `Layout/ParameterAlignment`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/IndentArray` cop has been renamed to `Layout/FirstArrayElementIndentation`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/IndentAssignment` cop has been renamed to `Layout/AssignmentIndentation`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/IndentFirstArgument` cop has been renamed to `Layout/FirstArgumentIndentation`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/IndentFirstArrayElement` cop has been renamed to `Layout/FirstArrayElementIndentation`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/IndentFirstHashElement` cop has been renamed to `Layout/FirstHashElementIndentation`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/IndentFirstParameter` cop has been renamed to `Layout/FirstParameterIndentation`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/IndentHash` cop has been renamed to `Layout/FirstHashElementIndentation`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/IndentHeredoc` cop has been renamed to `Layout/HeredocIndentation`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/LeadingBlankLines` cop has been renamed to `Layout/LeadingEmptyLines`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/Tab` cop has been renamed to `Layout/IndentationStyle`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/TrailingBlankLines` cop has been renamed to `Layout/TrailingEmptyLines`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/BlockAlignment` cop has been moved to `Layout/BlockAlignment`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/DefEndAlignment` cop has been moved to `Layout/DefEndAlignment`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/DuplicatedKey` cop has been renamed to `Lint/DuplicateHashKey`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/EndAlignment` cop has been moved to `Layout/EndAlignment`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/Eval` cop has been moved to `Security/Eval`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/HandleExceptions` cop has been renamed to `Lint/SuppressedException`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/MultipleCompare` cop has been renamed to `Lint/MultipleComparison`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/StringConversionInInterpolation` cop has been renamed to `Lint/RedundantStringCoercion`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/UnneededCopDisableDirective` cop has been renamed to `Lint/RedundantCopDisableDirective`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/UnneededCopEnableDirective` cop has been renamed to `Lint/RedundantCopEnableDirective`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/UnneededRequireStatement` cop has been renamed to `Lint/RedundantRequireStatement`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/UnneededSplatExpansion` cop has been renamed to `Lint/RedundantSplatExpansion`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Naming/UncommunicativeBlockParamName` cop has been renamed to `Naming/BlockParameterName`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Naming/UncommunicativeMethodParamName` cop has been renamed to `Naming/MethodParameterName`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/AccessorMethodName` cop has been moved to `Naming/AccessorMethodName`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/AsciiIdentifiers` cop has been moved to `Naming/AsciiIdentifiers`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/ClassAndModuleCamelCase` cop has been moved to `Naming/ClassAndModuleCamelCase`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/ConstantName` cop has been moved to `Naming/ConstantName`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/DeprecatedHashMethods` cop has been renamed to `Style/PreferredHashMethods`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/FileName` cop has been moved to `Naming/FileName`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/FlipFlop` cop has been moved to `Lint/FlipFlop`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/MethodCallParentheses` cop has been renamed to `Style/MethodCallWithoutArgsParentheses`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/MethodName` cop has been moved to `Naming/MethodName`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/OpMethod` cop has been renamed to `Naming/BinaryOperatorParameterName`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/SingleSpaceBeforeFirstArg` cop has been renamed to `Layout/SpaceBeforeFirstArg`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/UnneededCapitalW` cop has been renamed to `Style/RedundantCapitalW`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/UnneededCondition` cop has been renamed to `Style/RedundantCondition`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/UnneededInterpolation` cop has been renamed to `Style/RedundantInterpolation`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/UnneededPercentQ` cop has been renamed to `Style/RedundantPercentQ`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/UnneededSort` cop has been renamed to `Style/RedundantSort`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/VariableName` cop has been moved to `Naming/VariableName`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/VariableNumber` cop has been moved to `Naming/VariableNumber`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/SpaceAfterControlKeyword` cop has been removed. Please use `Layout/SpaceAroundKeyword` instead.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Layout/SpaceBeforeModifierKeyword` cop has been removed. Please use `Layout/SpaceAroundKeyword` instead.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/InvalidCharacterLiteral` cop has been removed since it was never being actually triggered.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/RescueWithoutErrorClass` cop has been removed. Please use `Style/RescueStandardError` instead.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/SpaceBeforeFirstArg` cop has been removed since it was a duplicate of `Layout/SpaceBeforeFirstArg`. Please use `Layout/SpaceBeforeFirstArg` instead.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/UselessComparison` cop has been removed since it has been superseded by `Lint/BinaryOperatorWithIdenticalOperands`. Please use `Lint/BinaryOperatorWithIdenticalOperands` instead.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/MethodMissingSuper` cop has been removed since it has been superseded by `Lint/MissingSuper`. Please use `Lint/MissingSuper` instead.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/SpaceAfterControlKeyword` cop has been removed. Please use `Layout/SpaceAroundKeyword` instead.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/SpaceBeforeModifierKeyword` cop has been removed. Please use `Layout/SpaceAroundKeyword` instead.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/TrailingComma` cop has been removed. Please use `Style/TrailingCommaInArguments`, `Style/TrailingCommaInArrayLiteral` and/or `Style/TrailingCommaInHashLiteral` instead.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/TrailingCommaInLiteral` cop has been removed. Please use `Style/TrailingCommaInArrayLiteral` and/or `Style/TrailingCommaInHashLiteral` instead.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Style/MethodMissing` cop has been split into `Style/MethodMissingSuper` and `Style/MissingRespondToMissing`.
(obsolete configuration found in example/.rubocop.yml, please update it)
OUTPUT
end
let(:expected_warnings) do
[
<<~OUTPUT.chomp
The `Style/PredicateName` cop has been renamed to `Naming/PredicatePrefix`.
(obsolete configuration found in example/.rubocop.yml, please update it)
OUTPUT
]
end
it 'prints a warning message' do
config_obsoletion.reject_obsolete!
raise 'Expected a RuboCop::ValidationError'
rescue RuboCop::ValidationError => e
expect(e.message).to eq(expected_message)
expect(config_obsoletion.warnings).to eq(expected_warnings)
end
end
context 'when the configuration includes any extracted cops' do
let(:hash) do
{
'Performance/Casecmp' => { Enabled: true },
'Performance/RedundantSortBlock' => { Enabled: true },
'Rails/Date' => { Enabled: true },
'Rails/DynamicFindBy' => { Enabled: true }
}
end
context 'when the plugin extensions are loaded' do
let(:plugins) { %w[rubocop-rails rubocop-performance] }
it 'does not print a warning message' do
expect { config_obsoletion.reject_obsolete! }.not_to raise_error
end
end
context 'when only one plugin extension is loaded' do
let(:plugins) { %w[rubocop-performance] }
let(:expected_message) do
<<~OUTPUT.chomp
`Rails` cops have been extracted to the `rubocop-rails` gem.
(obsolete configuration found in example/.rubocop.yml, please update it)
OUTPUT
end
it 'prints a warning message' do
config_obsoletion.reject_obsolete!
raise 'Expected a RuboCop::ValidationError'
rescue RuboCop::ValidationError => e
expect(e.message).to eq(expected_message)
end
end
context 'when the extensions are loaded' do
let(:requires) { %w[rubocop-rails rubocop-performance] }
it 'does not print a warning message' do
expect { config_obsoletion.reject_obsolete! }.not_to raise_error
end
end
context 'when only one extension is loaded' do
let(:requires) { %w[rubocop-performance] }
let(:expected_message) do
<<~OUTPUT.chomp
`Rails` cops have been extracted to the `rubocop-rails` gem.
(obsolete configuration found in example/.rubocop.yml, please update it)
OUTPUT
end
it 'prints a warning message' do
config_obsoletion.reject_obsolete!
raise 'Expected a RuboCop::ValidationError'
rescue RuboCop::ValidationError => e
expect(e.message).to eq(expected_message)
end
end
context 'when the extensions are not loaded' do
let(:expected_message) do
<<~OUTPUT.chomp
`Performance` cops have been extracted to the `rubocop-performance` gem.
(obsolete configuration found in example/.rubocop.yml, please update it)
`Rails` cops have been extracted to the `rubocop-rails` gem.
(obsolete configuration found in example/.rubocop.yml, please update it)
OUTPUT
end
it 'prints a warning message' do
config_obsoletion.reject_obsolete!
raise 'Expected a RuboCop::ValidationError'
rescue RuboCop::ValidationError => e
expect(e.message).to eq(expected_message)
end
end
end
context 'when the extensions are loaded via inherit_gem', :restore_registry do
include_context 'mock console output'
let(:resolver) { RuboCop::ConfigLoaderResolver.new }
let(:gem_root) { File.expand_path('gems') }
let(:hash) do
{
'inherit_gem' => { 'rubocop-includes' => '.rubocop.yml' },
'Performance/Casecmp' => { Enabled: true }
}
end
before do
create_file("#{gem_root}/rubocop-includes/.rubocop.yml", <<~YAML)
require:
- rubocop-performance
YAML
# Mock out a gem in order to test `inherit_gem`.
gem_class = Struct.new(:gem_dir)
mock_spec = gem_class.new(File.join(gem_root, 'rubocop-includes'))
allow(Gem::Specification).to receive(:find_by_name)
.with('rubocop-includes').and_return(mock_spec)
# Resolve `inherit_gem`
resolver.resolve_inheritance_from_gems(hash)
resolver.resolve_inheritance(loaded_path, hash, loaded_path, false)
allow(configuration).to receive(:loaded_features).and_call_original
end
it 'does not raise a ValidationError' do
expect { config_obsoletion.reject_obsolete! }.not_to raise_error
end
end
context 'when the configuration includes any obsolete parameters' do
before { allow(configuration).to receive(:loaded_features).and_return(%w[rubocop-rails]) }
let(:hash) do
{
'Layout/SpaceAroundOperators' => {
'MultiSpaceAllowedForOperators' => true
},
'Style/SpaceAroundOperators' => {
'MultiSpaceAllowedForOperators' => true
},
'Style/Encoding' => {
'EnforcedStyle' => 'a',
'SupportedStyles' => %w[a b c],
'AutoCorrectEncodingComment' => true
},
'Style/IfUnlessModifier' => { 'MaxLineLength' => 100 },
'Style/WhileUntilModifier' => { 'MaxLineLength' => 100 },
'AllCops' => { 'RunRailsCops' => true },
'Layout/CaseIndentation' => { 'IndentWhenRelativeTo' => 'end' },
'Layout/BlockAlignment' => { 'AlignWith' => 'end' },
'Layout/EndAlignment' => { 'AlignWith' => 'end' },
'Layout/DefEndAlignment' => { 'AlignWith' => 'end' },
'Rails/UniqBeforePluck' => { 'EnforcedMode' => 'x' },
# Moved cops with obsolete parameters
'Lint/BlockAlignment' => { 'AlignWith' => 'end' },
'Lint/EndAlignment' => { 'AlignWith' => 'end' },
'Lint/DefEndAlignment' => { 'AlignWith' => 'end' },
# Obsolete EnforcedStyles
'Layout/IndentationConsistency' => { 'EnforcedStyle' => 'rails' }
}
end
let(:expected_message) do
<<~OUTPUT.chomp
The `Lint/BlockAlignment` cop has been moved to `Layout/BlockAlignment`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/DefEndAlignment` cop has been moved to `Layout/DefEndAlignment`.
(obsolete configuration found in example/.rubocop.yml, please update it)
The `Lint/EndAlignment` cop has been moved to `Layout/EndAlignment`.
(obsolete configuration found in example/.rubocop.yml, please update it)
obsolete parameter `MultiSpaceAllowedForOperators` (for `Layout/SpaceAroundOperators`) found in example/.rubocop.yml
If your intention was to allow extra spaces for alignment, please use `AllowForAlignment: true` instead.
obsolete parameter `MultiSpaceAllowedForOperators` (for `Style/SpaceAroundOperators`) found in example/.rubocop.yml
If your intention was to allow extra spaces for alignment, please use `AllowForAlignment: true` instead.
obsolete parameter `EnforcedStyle` (for `Style/Encoding`) found in example/.rubocop.yml
`Style/Encoding` no longer supports styles. The "never" behavior is always assumed.
obsolete parameter `SupportedStyles` (for `Style/Encoding`) found in example/.rubocop.yml
`Style/Encoding` no longer supports styles. The "never" behavior is always assumed.
obsolete parameter `AutoCorrectEncodingComment` (for `Style/Encoding`) found in example/.rubocop.yml
`Style/Encoding` no longer supports styles. The "never" behavior is always assumed.
obsolete parameter `MaxLineLength` (for `Style/IfUnlessModifier`) found in example/.rubocop.yml
`Style/IfUnlessModifier: MaxLineLength` has been removed. Use `Layout/LineLength: Max` instead
obsolete parameter `MaxLineLength` (for `Style/WhileUntilModifier`) found in example/.rubocop.yml
`Style/WhileUntilModifier: MaxLineLength` has been removed. Use `Layout/LineLength: Max` instead
obsolete parameter `RunRailsCops` (for `AllCops`) found in example/.rubocop.yml
Use the following configuration instead:
Rails:
Enabled: true
obsolete parameter `IndentWhenRelativeTo` (for `Layout/CaseIndentation`) found in example/.rubocop.yml
`IndentWhenRelativeTo` has been renamed to `EnforcedStyle`.
obsolete parameter `AlignWith` (for `Lint/BlockAlignment`) found in example/.rubocop.yml
`AlignWith` has been renamed to `EnforcedStyleAlignWith`.
obsolete parameter `AlignWith` (for `Layout/BlockAlignment`) found in example/.rubocop.yml
`AlignWith` has been renamed to `EnforcedStyleAlignWith`.
obsolete parameter `AlignWith` (for `Lint/EndAlignment`) found in example/.rubocop.yml
`AlignWith` has been renamed to `EnforcedStyleAlignWith`.
obsolete parameter `AlignWith` (for `Layout/EndAlignment`) found in example/.rubocop.yml
`AlignWith` has been renamed to `EnforcedStyleAlignWith`.
obsolete parameter `AlignWith` (for `Lint/DefEndAlignment`) found in example/.rubocop.yml
`AlignWith` has been renamed to `EnforcedStyleAlignWith`.
obsolete parameter `AlignWith` (for `Layout/DefEndAlignment`) found in example/.rubocop.yml
`AlignWith` has been renamed to `EnforcedStyleAlignWith`.
obsolete parameter `EnforcedMode` (for `Rails/UniqBeforePluck`) found in example/.rubocop.yml
`EnforcedMode` has been renamed to `EnforcedStyle`.
obsolete `EnforcedStyle: rails` (for `Layout/IndentationConsistency`) found in example/.rubocop.yml
`EnforcedStyle: rails` has been renamed to `EnforcedStyle: indented_internal_methods`.
OUTPUT
end
it 'prints an error message' do
config_obsoletion.reject_obsolete!
raise 'Expected a RuboCop::ValidationError'
rescue RuboCop::ValidationError => e
expect(e.message).to eq(expected_message)
end
end
context 'when the configuration includes deprecated parameters for the TargetRubyVersion' do
let(:hash) do
{
'AllCops' => { 'TargetRubyVersion' => target_ruby_version },
**cop_config
}
end
let(:warning_message) { config_obsoletion.warnings.join("\n") }
context 'with Style/ArgumentsForwarding AllowOnlyRestArgument' do
let(:cop_config) do
{ 'Style/ArgumentsForwarding' => { 'AllowOnlyRestArgument' => false } }
end
context 'with TargetRubyVersion 3.2' do
let(:target_ruby_version) { 3.2 }
it 'prints a warning message' do
expected_message = <<~OUTPUT.chomp
obsolete parameter `AllowOnlyRestArgument` (for `Style/ArgumentsForwarding`) found in example/.rubocop.yml
`AllowOnlyRestArgument` has no effect with TargetRubyVersion >= 3.2.
OUTPUT
expect { config_obsoletion.reject_obsolete! }.not_to raise_error
expect(warning_message).to eq(expected_message)
end
end
context 'with TargetRubyVersion 3.1' do
let(:target_ruby_version) { 3.1 }
it 'does not print a warning message' do
expect { config_obsoletion.reject_obsolete! }.not_to raise_error
expect(warning_message).to eq('')
end
end
end
end
context 'when the configuration includes any deprecated parameters' do
let(:hash) do
{
'Lint/AmbiguousBlockAssociation' => {
'IgnoredMethods' => %w[foo bar]
},
'Lint/NumberConversion' => {
'IgnoredMethods' => %w[foo bar]
},
'Metrics/AbcSize' => {
'IgnoredMethods' => %w[foo bar]
},
'Metrics/BlockLength' => {
'ExcludedMethods' => %w[foo bar],
'IgnoredMethods' => %w[foo bar]
},
'Metrics/CyclomaticComplexity' => {
'IgnoredMethods' => %w[foo bar]
},
'Metrics/MethodLength' => {
'ExcludedMethods' => %w[foo bar],
'IgnoredMethods' => %w[foo bar]
},
'Metrics/PerceivedComplexity' => {
'IgnoredMethods' => %w[foo bar]
},
'Style/BlockDelimiters' => {
'IgnoredMethods' => %w[foo bar]
},
'Style/ClassEqualityComparison' => {
'IgnoredMethods' => %w[foo bar]
},
'Style/FormatStringToken' => {
'IgnoredMethods' => %w[foo bar]
},
'Style/MethodCallWithArgsParentheses' => {
'IgnoredMethods' => %w[foo bar]
},
'Style/MethodCallWithoutArgsParentheses' => {
'IgnoredMethods' => %w[foo bar]
},
'Style/NumericPredicate' => {
'IgnoredMethods' => %w[foo bar]
},
'Style/SymbolLiteral' => {
'IgnoredMethods' => %w[foo bar]
}
}
end
let(:warning_message) { config_obsoletion.warnings.join("\n") }
let(:expected_message) do
<<~OUTPUT.chomp
obsolete parameter `ExcludedMethods` (for `Metrics/BlockLength`) found in example/.rubocop.yml
`ExcludedMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `ExcludedMethods` (for `Metrics/MethodLength`) found in example/.rubocop.yml
`ExcludedMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Lint/AmbiguousBlockAssociation`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Lint/NumberConversion`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Metrics/AbcSize`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Metrics/BlockLength`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Metrics/CyclomaticComplexity`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Metrics/MethodLength`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Metrics/PerceivedComplexity`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Style/BlockDelimiters`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Style/ClassEqualityComparison`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Style/FormatStringToken`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Style/MethodCallWithArgsParentheses`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Style/MethodCallWithoutArgsParentheses`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Style/NumericPredicate`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
obsolete parameter `IgnoredMethods` (for `Style/SymbolLiteral`) found in example/.rubocop.yml
`IgnoredMethods` has been renamed to `AllowedMethods` and/or `AllowedPatterns`.
OUTPUT
end
it 'prints a warning message' do
expect { config_obsoletion.reject_obsolete! }.not_to raise_error
expect(warning_message).to eq(expected_message)
end
end
context 'when additional obsoletions are defined externally' do
let(:hash) do
{
'Foo/Bar' => { Enabled: true },
'Vegetable/Tomato' => { Enabled: true },
'Legacy/Test' => { Enabled: true },
'Other/Cop' => { Enabled: true },
'Style/FlipFlop' => { Enabled: true }
}
end
let(:file_with_renamed_config) do
create_file('obsoletions1.yml', <<~YAML)
renamed:
Foo/Bar: Foo/Baz
Vegetable/Tomato: Fruit/Tomato
YAML
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cli_spec.rb | spec/rubocop/cli_spec.rb | # frozen_string_literal: true
require 'timeout'
RSpec.describe RuboCop::CLI, :isolated_environment do
subject(:cli) { described_class.new }
include_context 'cli spec behavior'
context 'when interrupted' do
it 'returns 130' do
allow_any_instance_of(RuboCop::Runner).to receive(:aborting?).and_return(true)
create_empty_file('example.rb')
expect(cli.run(['example.rb'])).to eq(130)
end
end
context 'when given a file/directory that is not under the current dir' do
shared_examples 'checks Rakefile' do
it 'checks a Rakefile but Style/FileName does not report' do
create_file('Rakefile', <<~RUBY)
# frozen_string_literal: true
x = 1
RUBY
create_empty_file('other/empty')
Dir.chdir('other') { expect(cli.run(['--format', 'simple', checked_path])).to eq(1) }
expect($stdout.string).to eq(<<~RESULT)
== #{abs('Rakefile')} ==
W: 3: 1: [Correctable] Lint/UselessAssignment: Useless assignment to variable - x.
1 file inspected, 1 offense detected, 1 offense autocorrectable
RESULT
end
end
context 'and the directory is absolute' do
let(:checked_path) { abs('..') }
it_behaves_like 'checks Rakefile'
end
context 'and the directory is relative' do
let(:checked_path) { '..' }
it_behaves_like 'checks Rakefile'
end
context 'and the Rakefile path is absolute' do
let(:checked_path) { abs('../Rakefile') }
it_behaves_like 'checks Rakefile'
end
context 'and the Rakefile path is relative' do
let(:checked_path) { '../Rakefile' }
it_behaves_like 'checks Rakefile'
end
end
context 'when lines end with CR+LF' do
it 'reports an offense' do
create_file('example.rb', <<~RUBY)
x = 0\r
puts x\r
RUBY
# Make Style/EndOfLine give same output regardless of platform.
create_file('.rubocop.yml', <<~YAML)
EndOfLine:
EnforcedStyle: lf
YAML
result = cli.run(['--format', 'simple', 'example.rb'])
expect(result).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
== example.rb ==
C: 1: 1: Layout/EndOfLine: Carriage return character detected.
C: 1: 1: [Correctable] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
1 file inspected, 2 offenses detected, 1 offense autocorrectable
RESULT
expect($stderr.string).to eq(<<~RESULT)
#{abs('.rubocop.yml')}: Warning: no department given for EndOfLine.
RESULT
end
end
context 'when using an invalid encoding string' do
it 'does not crash and reports an offense' do
create_file('example.rb', <<~'RUBY')
"\xE3\xD3\x8B\xE3\x83\xBC\x83\xE3\x83\xE3\x82\xB3\xA3\x82\x99"
RUBY
result = cli.run(['--format', 'simple', 'example.rb'])
expect(result).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
== example.rb ==
C: 1: 1: [Correctable] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
1 file inspected, 1 offense detected, 1 offense autocorrectable
RESULT
expect($stderr.string).to eq ''
end
end
context 'when checking a correct file' do
it 'returns 0' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
x = 0
puts x
RUBY
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(0)
expect($stdout.string)
.to eq(<<~RESULT)
1 file inspected, no offenses detected
RESULT
end
context 'when super is used with a block' do
it 'still returns 0' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
# this is a class
class Thing
def super_with_block
super { |response| }
end
def and_with_args
super(arg1, arg2) { |response| }
end
end
RUBY
create_file('.rubocop.yml', <<~YAML)
Lint/UnusedBlockArgument:
IgnoreEmptyBlocks: true
YAML
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(0)
expect($stdout.string)
.to eq(<<~RESULT)
1 file inspected, no offenses detected
RESULT
end
end
end
it 'checks a given file with faults and returns 1' do
create_file('example.rb', ['# frozen_string_literal: true', '', 'x = 0 ', 'puts x'])
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(1)
expect($stdout.string)
.to eq <<~RESULT
== example.rb ==
C: 3: 6: [Correctable] Layout/TrailingWhitespace: Trailing whitespace detected.
1 file inspected, 1 offense detected, 1 offense autocorrectable
RESULT
end
it 'registers an offense for a syntax error' do
create_file('example.rb', ['class Test', 'en'])
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stderr.string).to eq ''
expect($stdout.string)
.to eq(["#{abs('example.rb')}:3:1: F: Lint/Syntax: unexpected " \
'token $end (Using Ruby 2.7 parser; configure using ' \
'`TargetRubyVersion` parameter, under `AllCops`)',
''].join("\n"))
end
it 'registers an offense for Parser warnings' do
create_file('example.rb', [
'# frozen_string_literal: true',
'',
'puts *test',
'if a then b else c end'
])
aggregate_failures('CLI output') do
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stdout.string)
.to eq(["#{abs('example.rb')}:3:6: W: [Correctable] Lint/AmbiguousOperator: " \
'Ambiguous splat operator. Parenthesize the method arguments ' \
"if it's surely a splat operator, or add a whitespace to the " \
'right of the `*` if it should be a multiplication.',
"#{abs('example.rb')}:4:1: C: [Correctable] Style/OneLineConditional: " \
'Favor the ternary operator (`?:`) over single-line `if/then/else/end` constructs.',
''].join("\n"))
end
end
it 'can process a file with an invalid UTF-8 byte sequence' do
create_file('example.rb', ["# #{'f9'.hex.chr}#{'29'.hex.chr}"])
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stderr.string).to eq ''
expect($stdout.string)
.to eq(<<~RESULT)
#{abs('example.rb')}:1:1: F: Lint/Syntax: Invalid byte sequence in utf-8.
RESULT
end
context 'when errors are raised while processing files due to bugs' do
let(:errors) { ['An error occurred while Encoding cop was inspecting file.rb.'] }
before { allow_any_instance_of(RuboCop::Runner).to receive(:errors).and_return(errors) }
it 'displays an error message to stderr' do
cli.run([])
expect($stderr.string).to include('1 error occurred:').and include(errors.first)
end
end
if RUBY_ENGINE == 'ruby' && !RuboCop::Platform.windows?
# NOTE: It has been tested for parallelism with `--debug` option.
# In other words, even if no option is specified, it will be parallelized by default.
describe 'when parallel static by default' do
context 'when specifying `--debug` option only`' do
it 'uses parallel inspection' do
create_file('example1.rb', <<~RUBY)
# frozen_string_literal: true
puts 'hello'
RUBY
expect(cli.run(['--debug'])).to eq(0)
expect($stdout.string).to include('Use parallel by default.')
end
end
context 'when specifying configuration file' do
it 'uses parallel inspection' do
create_file('example1.rb', <<~RUBY)
# frozen_string_literal: true
puts 'hello'
RUBY
create_empty_file('.rubocop.yml')
expect(cli.run(['--debug', '--config', '.rubocop.yml'])).to eq(0)
expect($stdout.string).to include('Use parallel by default.')
end
end
context 'when specifying `--debug` and `-a` options`' do
it 'uses parallel inspection when correcting the file' do
create_file('example1.rb', <<~RUBY)
# frozen_string_literal: true
puts "hello"
RUBY
expect(cli.run(['--debug', '-a'])).to eq(0)
expect($stdout.string).to include('Use parallel by default.')
expect(File.read('example1.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
puts 'hello'
RUBY
end
end
context 'when setting `UseCache: true`' do
it 'uses parallel inspection' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
puts 'hello'
RUBY
create_file('.rubocop.yml', <<~YAML)
AllCops:
UseCache: true
YAML
expect(cli.run(['--debug'])).to eq(0)
expect($stdout.string).to include('Use parallel by default.')
end
end
context 'when setting `UseCache: false`' do
it 'does not use parallel inspection' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
puts 'hello'
RUBY
create_file('.rubocop.yml', <<~YAML)
AllCops:
UseCache: false
YAML
expect(cli.run(['--debug'])).to eq(0)
expect($stdout.string).not_to include('Use parallel by default.')
end
end
end
context 'when a directory is named `*`' do
before do
FileUtils.mkdir('*')
end
after do
FileUtils.rmdir('*')
end
it 'does not crash' do
expect(cli.run([])).to eq(0)
end
end
end
describe 'for a disabled cop' do
it 'reports an offense when explicitly enabled on part of a file' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
SuggestExtensions: false
Lint/UselessAssignment:
Enabled: false
YAML
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
a = 1
# rubocop:enable Lint/UselessAssignment
b = 2
# rubocop:disable Lint/UselessAssignment
c = 3
RUBY
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
== example.rb ==
W: 5: 1: [Correctable] Lint/UselessAssignment: Useless assignment to variable - b.
1 file inspected, 1 offense detected, 1 offense autocorrectable
RESULT
end
it '`Lint/Syntax` must be enabled when `Lint` is given `Enabled: false`' do
create_file('.rubocop.yml', <<~YAML)
Lint:
Enabled: false
YAML
create_file('example.rb', <<~RUBY)
1 /// 2
RUBY
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(1)
expect($stdout.string).to include('F: 1: 7: Lint/Syntax: unexpected token tINTEGER')
end
it '`Lint/Syntax` must be enabled when `DisabledByDefault: true`' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
DisabledByDefault: true
YAML
create_file('example.rb', <<~RUBY)
1 /// 2
RUBY
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(1)
expect($stdout.string).to include('F: 1: 7: Lint/Syntax: unexpected token tINTEGER')
end
it '`Lint/Syntax` must be enabled when disabled by directive comment' do
create_file('example.rb', <<~RUBY)
# rubocop:disable Lint/Syntax
1 /// 2
RUBY
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(1)
expect($stdout.string).to include('F: 2: 7: Lint/Syntax: unexpected token tINTEGER')
end
it '`Lint/Syntax` must be enabled when disabled by directive department comment' do
create_file('example.rb', <<~RUBY)
# rubocop:disable Lint
1 /// 2
RUBY
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(1)
expect($stdout.string).to include('F: 2: 7: Lint/Syntax: unexpected token tINTEGER')
end
it '`Lint/Syntax` must be enabled when disabled by directive all comment' do
create_file('example.rb', <<~RUBY)
# rubocop:disable all
1 /// 2
RUBY
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(1)
expect($stdout.string).to include('F: 2: 7: Lint/Syntax: unexpected token tINTEGER')
end
it '`Naming/FileName` must be be disabled for global offenses' do
create_file('Example.rb', <<~RUBY)
# rubocop:disable Naming/FileName
RUBY
expect(cli.run(['--format', 'simple', 'Example.rb'])).to eq(1)
expect($stdout.string).not_to include('Naming/FileName:')
end
it '`Naming/FileName` must be be enabled if directive comment is on unrelated line' do
create_file('Example.rb', <<~RUBY)
# Prelude
# rubocop:disable Naming/FileName
RUBY
expect(cli.run(['--format', 'simple', 'Example.rb'])).to eq(1)
expect($stdout.string).to include('C: 1: 1: Naming/FileName:')
end
end
describe 'for a cop enabled only for a subset of files' do
it "doesn't enable the cop for all files when department disables are present" do
create_file('.rubocop.yml', <<~YAML)
AllCops:
DisabledByDefault: true
Style/HashSyntax:
Enabled: true
Exclude:
- example1.rb
YAML
source = <<~RUBY
{ :a => :b }
# rubocop:disable Style
{ :a => :b }
# rubocop:enable Style
# rubocop:disable all
{ :a => :b }
# rubocop:enable all
RUBY
create_file('example1.rb', source)
create_file('example2.rb', source)
expect(cli.run(['--format', 'simple', 'example1.rb', 'example2.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
== example2.rb ==
C: 1: 3: [Correctable] Style/HashSyntax: Use the new Ruby 1.9 hash syntax.
2 files inspected, 1 offense detected, 1 offense autocorrectable
RESULT
end
end
describe 'rubocop:disable comment' do
it 'can disable all cops in a code section' do
src = ['# rubocop:disable all',
'#' * 130,
'x(123456)',
'y("123")',
'def func',
' # rubocop: enable Layout/LineLength,Style/StringLiterals',
" #{'#' * 130}",
' x(123456)',
' y("123")',
'end']
create_file('example.rb', src)
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
# all cops were disabled, then 2 were enabled again, so we
# should get 2 offenses reported.
expect($stdout.string).to eq(<<~RESULT)
#{abs('example.rb')}:7:121: C: Layout/LineLength: Line is too long. [132/120]
#{abs('example.rb')}:9:5: C: [Correctable] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.
RESULT
end
describe 'Specify `--init` option to `rubocop` command' do
context 'when .rubocop.yml does not exist' do
it 'generate a .rubocop.yml file' do
expect(cli.run(['--init'])).to eq(0)
expect($stdout.string).to start_with('Writing new .rubocop.yml to')
expect(File.read('.rubocop.yml')).to eq(<<~YAML)
# The behavior of RuboCop can be controlled via the .rubocop.yml
# configuration file. It makes it possible to enable/disable
# certain cops (checks) and to alter their behavior if they accept
# any parameters. The file can be placed either in your home
# directory or in some project directory.
#
# RuboCop will start looking for the configuration file in the directory
# where the inspected file is and continue its way up to the root directory.
#
# See https://docs.rubocop.org/rubocop/configuration
YAML
end
end
context 'when .rubocop.yml already exists' do
it 'fails with an error message' do
create_empty_file('.rubocop.yml')
expect(cli.run(['--init'])).to eq(2)
expect($stderr.string).to start_with('.rubocop.yml already exists at')
end
end
end
context 'when --autocorrect-all is given' do
it 'does not trigger RedundantCopDisableDirective due to lines moving around' do
src = ['a = 1 # rubocop:disable Lint/UselessAssignment']
create_file('example.rb', src)
create_file('.rubocop.yml', <<~YAML)
Style/FrozenStringLiteralComment:
Enabled: true
EnforcedStyle: always
Layout/EmptyLineAfterMagicComment:
Enabled: false
YAML
expect(cli.run(['--format', 'offenses', '-A', 'example.rb'])).to eq(0)
expect($stdout.string).to eq(<<~RESULT)
1 Style/FrozenStringLiteralComment [Unsafe Correctable]
--
1 Total in 1 files
RESULT
expect(File.read('example.rb'))
.to eq(<<~RUBY)
# frozen_string_literal: true
a = 1 # rubocop:disable Lint/UselessAssignment
RUBY
end
end
it 'can disable selected cops in a code section' do
create_file('example.rb',
['# frozen_string_literal: true',
'',
'# rubocop:disable Style/LineLength,' \
'Style/NumericLiterals,Style/StringLiterals',
'#' * 130,
'x(123456)',
'y("123")',
'def func',
' # rubocop: enable Layout/LineLength, ' \
'Style/StringLiterals',
" #{'#' * 130}",
' x(123456)',
' y("123")',
' # rubocop: enable Style/NumericLiterals',
'end'])
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stderr.string)
.to eq(['example.rb: Style/LineLength has the wrong ' \
'namespace - replace it with Layout/LineLength',
''].join("\n"))
# 2 real cops were disabled, and 1 that was incorrect
# 2 real cops was enabled, but only 1 had been disabled correctly
expect($stdout.string).to eq(<<~RESULT)
#{abs('example.rb')}:8:21: W: [Correctable] Lint/RedundantCopEnableDirective: Unnecessary enabling of Layout/LineLength.
#{abs('example.rb')}:9:121: C: Layout/LineLength: Line is too long. [132/120]
#{abs('example.rb')}:11:5: C: [Correctable] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.
RESULT
end
it 'can disable all cops on a single line' do
create_file('example.rb', 'y("123", 123456) # rubocop:disable all')
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(0)
expect($stdout.string).to be_empty
end
it 'can disable selected cops on a single line' do
create_file('example.rb',
['# frozen_string_literal: true',
'',
"#{'a' * 130} # rubocop:disable Layout/LineLength",
'#' * 130,
'y("123", 123456) # rubocop:disable Style/StringLiterals,' \
'Style/NumericLiterals'])
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
#{abs('example.rb')}:4:121: C: Layout/LineLength: Line is too long. [130/120]
RESULT
end
context 'without using namespace' do
it 'can disable selected cops on a single line but prints a warning' do
create_file('example.rb',
['# frozen_string_literal: true',
'',
"#{'a' * 130} # rubocop:disable LineLength",
'#' * 130,
'y("123") # rubocop:disable StringLiterals'])
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stderr.string).to eq(<<~OUTPUT)
#{abs('example.rb')}: Warning: no department given for LineLength. Run `rubocop -a --only Migration/DepartmentName` to fix.
#{abs('example.rb')}: Warning: no department given for StringLiterals. Run `rubocop -a --only Migration/DepartmentName` to fix.
OUTPUT
expect($stdout.string)
.to eq(<<~RESULT)
#{abs('example.rb')}:3:150: C: [Correctable] Migration/DepartmentName: Department name is missing.
#{abs('example.rb')}:4:121: C: Layout/LineLength: Line is too long. [130/120]
#{abs('example.rb')}:5:28: C: [Correctable] Migration/DepartmentName: Department name is missing.
RESULT
end
end
context 'when not necessary' do
it 'causes an offense to be reported' do
create_file('example.rb',
['# frozen_string_literal: true',
'',
'#' * 130,
'# rubocop:disable all',
"#{'a' * 10} # rubocop:disable Layout/LineLength,Metrics/ClassLength",
'y(123) # rubocop:disable all',
'# rubocop:enable all'])
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~RESULT)
#{abs('example.rb')}:3:121: C: Layout/LineLength: Line is too long. [130/120]
#{abs('example.rb')}:4:1: W: [Correctable] Lint/RedundantCopDisableDirective: Unnecessary disabling of all cops.
#{abs('example.rb')}:5:12: W: [Correctable] Lint/RedundantCopDisableDirective: Unnecessary disabling of `Layout/LineLength`, `Metrics/ClassLength`.
#{abs('example.rb')}:6:8: W: [Correctable] Lint/RedundantCopDisableDirective: Unnecessary disabling of all cops.
RESULT
end
context 'and there are no other offenses' do
it 'exits with error code' do
create_file('example.rb', "#{'a' * 10} # rubocop:disable LineLength")
expect(cli.run(['example.rb'])).to eq(1)
end
end
context 'when using `rubocop:disable` line comment for `Lint/EmptyBlock`' do
it 'does not register an offense for `Lint/RedundantCopDisableDirective`' do
create_file('.rubocop.yml', <<~YAML)
Lint/EmptyBlock:
Enabled: true
Lint/RedundantCopDisableDirective:
Enabled: true
YAML
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
assert_equal nil, combinator {}.call # rubocop:disable Lint/EmptyBlock'
RUBY
expect(cli.run(['example.rb'])).to eq(0)
expect($stdout.string).to include('1 file inspected, no offenses detected')
end
end
context 'when using `rubocop:disable` line comment for `Style/RedundantInitialize`' do
it 'does not register an offense for `Lint/RedundantCopDisableDirective`' do
create_file('.rubocop.yml', <<~YAML)
Style/RedundantInitialize:
Enabled: true
Lint/RedundantCopDisableDirective:
Enabled: true
YAML
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
Class.new do
def initialize; end # rubocop:disable Style/RedundantInitialize
end
RUBY
expect(cli.run(['example.rb'])).to eq(0)
expect($stdout.string).to include('1 file inspected, no offenses detected')
end
end
shared_examples 'RedundantCopDisableDirective not run' do |state, config|
context "and RedundantCopDisableDirective is #{state}" do
it 'does not report RedundantCopDisableDirective offenses' do
create_file('example.rb',
['# frozen_string_literal: true',
'',
'#' * 130,
'# rubocop:disable all',
"#{'a' * 10} # rubocop:disable LineLength,ClassLength",
'y(123) # rubocop:disable all'])
create_file('.rubocop.yml', config)
expect(cli.run(['--format', 'emacs'])).to eq(1)
expect($stderr.string).to eq(<<~OUTPUT)
#{abs('example.rb')}: Warning: no department given for LineLength. Run `rubocop -a --only Migration/DepartmentName` to fix.
#{abs('example.rb')}: Warning: no department given for ClassLength. Run `rubocop -a --only Migration/DepartmentName` to fix.
OUTPUT
expect($stdout.string)
.to eq(<<~RESULT)
#{abs('example.rb')}:3:121: C: Layout/LineLength: Line is too long. [130/120]
RESULT
end
end
end
it_behaves_like 'RedundantCopDisableDirective not run',
'individually disabled', <<~YAML
Lint/RedundantCopDisableDirective:
Enabled: false
YAML
it_behaves_like 'RedundantCopDisableDirective not run',
'individually excluded', <<~YAML
Lint/RedundantCopDisableDirective:
Exclude:
- example.rb
YAML
it_behaves_like 'RedundantCopDisableDirective not run',
'disabled through department', <<~YAML
Lint:
Enabled: false
YAML
end
end
it 'finds a file with no .rb extension but has a shebang line' do
allow_any_instance_of(File::Stat).to receive(:executable?).and_return(true)
create_file('example', ['#!/usr/bin/env ruby', 'x = 0', 'puts x'])
create_file('.rubocop.yml', <<~YAML)
Style/FrozenStringLiteralComment:
Enabled: false
YAML
expect(cli.run(%w[--format simple])).to eq(0)
expect($stdout.string).to eq(['', '1 file inspected, no offenses detected', ''].join("\n"))
end
it 'does not register any offenses for an empty file' do
create_empty_file('example.rb')
expect(cli.run(%w[--format simple])).to eq(0)
expect($stdout.string).to eq(['', '1 file inspected, no offenses detected', ''].join("\n"))
end
describe 'style guide only usage' do
context 'via the cli option' do
describe '--only-guide-cops' do
it 'skips cops that have no link to a style guide' do
create_file('example.rb', 'raise')
create_file('.rubocop.yml', <<~YAML)
Layout/LineLength:
Enabled: true
StyleGuide: ~
Max: 2
YAML
expect(cli.run(['--format', 'simple', '--only-guide-cops', 'example.rb'])).to eq(0)
end
it 'runs cops for rules that link to a style guide' do
create_file('example.rb', 'raise')
create_file('.rubocop.yml', <<~YAML)
Layout/LineLength:
Enabled: true
StyleGuide: "http://an.example/url"
Max: 2
YAML
expect(cli.run(['--format', 'simple', '--only-guide-cops', 'example.rb'])).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
== example.rb ==
C: 1: 3: Layout/LineLength: Line is too long. [5/2]
1 file inspected, 1 offense detected
RESULT
end
it 'overrides configuration of AllCops/StyleGuideCopsOnly' do
create_file('example.rb', 'raise')
create_file('.rubocop.yml', <<~YAML)
AllCops:
StyleGuideCopsOnly: false
Layout/LineLength:
Enabled: true
StyleGuide: ~
Max: 2
YAML
expect(cli.run(['--format', 'simple', '--only-guide-cops', 'example.rb'])).to eq(0)
end
end
end
context 'via the config' do
before do
create_file('example.rb', <<~RUBY)
if foo and bar
do_something
end
RUBY
create_file('.rubocop.yml', <<~YAML)
AllCops:
StyleGuideCopsOnly: #{guide_cops_only}
DisabledByDefault: #{disabled_by_default}
Layout/LineLength:
Enabled: true
StyleGuide: ~
Max: 2
Style/FrozenStringLiteralComment:
Enabled: false
YAML
end
describe 'AllCops/StyleGuideCopsOnly' do
let(:disabled_by_default) { 'false' }
context 'when it is true' do
let(:guide_cops_only) { 'true' }
it 'skips cops that have no link to a style guide' do
expect(cli.run(['--format', 'offenses', 'example.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
1 Style/AndOr [Unsafe Correctable]
--
1 Total in 1 files
RESULT
end
end
context 'when it is false' do
let(:guide_cops_only) { 'false' }
it 'runs cops for rules regardless of any link to the style guide' do
expect(cli.run(['--format', 'offenses', 'example.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
3 Layout/LineLength [Safe Correctable]
1 Style/AndOr [Unsafe Correctable]
--
4 Total in 1 files
RESULT
end
end
end
describe 'AllCops/DisabledByDefault' do
let(:guide_cops_only) { 'false' }
context 'when it is true' do
let(:disabled_by_default) { 'true' }
it 'runs only the cop configured in .rubocop.yml' do
expect(cli.run(['--format', 'offenses', 'example.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
3 Layout/LineLength [Safe Correctable]
--
3 Total in 1 files
RESULT
end
end
context 'when it is false' do
let(:disabled_by_default) { 'false' }
it 'runs all cops that are enabled in default configuration' do
expect(cli.run(['--format', 'offenses', 'example.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
3 Layout/LineLength [Safe Correctable]
1 Style/AndOr [Unsafe Correctable]
--
4 Total in 1 files
RESULT
end
end
end
end
end
describe 'cops can exclude files based on config' do
it 'ignores excluded files' do
create_file('example.rb', 'x = 0')
create_file('regexp.rb', 'x = 0')
create_file('exclude_glob.rb', ['#!/usr/bin/env ruby', 'x = 0'])
create_file('dir/thing.rb', 'x = 0')
create_file('.rubocop.yml', <<~'YAML')
Lint/UselessAssignment:
Exclude:
- example.rb
- !ruby/regexp /regexp.rb\z/
- "exclude_*"
- "dir/*"
Style/FrozenStringLiteralComment:
Enabled: false
YAML
allow_any_instance_of(File::Stat).to receive(:executable?).and_return(true)
expect(cli.run(%w[--format simple])).to eq(0)
expect($stdout.string).to eq(['', '4 files inspected, no offenses detected', ''].join("\n"))
end
end
describe 'configuration from file' do
before { RuboCop::ConfigLoader.default_configuration = nil }
context 'when a value in a hash is overridden with nil' do
it 'acts as if the key/value pair was removed' do
create_file('.rubocop.yml', <<~YAML)
Style/InverseMethods:
InverseMethods:
:even?: ~
Style/CollectionMethods:
Enabled: true
PreferredMethods:
collect: ~
Style/FrozenStringLiteralComment:
Enabled: false
YAML
create_file('example.rb', 'array.collect { |e| !e.odd? }')
expect(cli.run([])).to eq(0)
end
end
context 'when configured for indented_internal_methods style indentation' do
it 'accepts indented_internal_methods style indentation' do
create_file('.rubocop.yml', <<~YAML)
Layout/IndentationConsistency:
EnforcedStyle: indented_internal_methods
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/comment_config_spec.rb | spec/rubocop/comment_config_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::CommentConfig do
subject(:comment_config) { described_class.new(parse_source(source)) }
describe '#cop_enabled_at_line?' do
let(:source) do
# rubocop:disable Lint/EmptyExpression, Lint/EmptyInterpolation
<<~RUBY
# rubocop:disable Metrics/MethodLength with a comment why
def some_method
puts 'foo' # 03
end
# rubocop:enable Metrics/MethodLength
# rubocop:disable all
some_method # 08
# rubocop:enable all
code = 'This is evil.'
eval(code) # rubocop:disable Security/Eval
puts 'This is not evil.' # 12
def some_method
puts 'Disabling indented single line' # rubocop:disable Layout/LineLength
end
# 18
string = <<~END
This is a string not a real comment # rubocop:disable Style/Loop
END
foo # rubocop:disable Style/MethodCallWithoutArgsParentheses # 23
# rubocop:enable Lint/Void
# rubocop:disable Style/For, Style/Not,Layout/IndentationStyle
foo # 28
class One
# rubocop:disable Style/ClassVars
@@class_var = 1
end # 33
class Two
# rubocop:disable Style/ClassVars
@@class_var = 2
end # 38
# rubocop:enable Style/Not,Layout/IndentationStyle
# rubocop:disable Style/Send, Lint/RandOne some comment why
# rubocop:disable Layout/BlockAlignment some comment why
# rubocop:enable Style/Send, Layout/BlockAlignment but why?
# rubocop:enable Lint/RandOne foo bar! # 43
# rubocop:disable Lint/EmptyInterpolation
"result is #{}"
# rubocop:enable Lint/EmptyInterpolation
# rubocop:disable RSpec/Example
# rubocop:disable Custom2/Number9 # 48
#=SomeDslDirective # rubocop:disable Layout/LeadingCommentSpace
# rubocop:disable RSpec/Rails/HttpStatus
it { is_expected.to have_http_status 200 } # 52
# rubocop:enable RSpec/Rails/HttpStatus
RUBY
# rubocop:enable Lint/EmptyExpression, Lint/EmptyInterpolation
end
def disabled_lines_of_cop(cop)
(1..source.size).each_with_object([]) do |line_number, disabled_lines|
enabled = comment_config.cop_enabled_at_line?(cop, line_number)
disabled_lines << line_number unless enabled
end
end
it 'supports disabling multiple lines with a pair of directive' do
method_length_disabled_lines = disabled_lines_of_cop('Metrics/MethodLength')
expected_part = (1..4).to_a
expect(method_length_disabled_lines & expected_part).to eq(expected_part)
end
it 'supports enabling/disabling multiple cops in a single directive' do
not_disabled_lines = disabled_lines_of_cop('Style/Not')
tab_disabled_lines = disabled_lines_of_cop('Layout/IndentationStyle')
expect(not_disabled_lines).to eq(tab_disabled_lines)
expected_part = (27..39).to_a
expect(not_disabled_lines & expected_part).to eq(expected_part)
end
it 'supports enabling/disabling multiple cops along with a comment' do
{
'Style/Send' => 40..42,
'Lint/RandOne' => 40..43,
'Layout/BlockAlignment' => 41..42
}.each do |cop_name, expected|
actual = disabled_lines_of_cop(cop_name)
expect(actual & expected.to_a).to eq(expected.to_a)
end
end
it 'supports disabling cops with multiple levels in department name' do
disabled_lines = disabled_lines_of_cop('RSpec/Rails/HttpStatus')
expected_part = (51..53).to_a
expect(disabled_lines & expected_part).to eq(expected_part)
end
it 'supports enabling/disabling cops without a prefix' do
empty_interpolation_disabled_lines = disabled_lines_of_cop('Lint/EmptyInterpolation')
expected = (44..46).to_a
expect(empty_interpolation_disabled_lines & expected).to eq(expected)
end
it 'supports disabling all lines after a directive' do
for_disabled_lines = disabled_lines_of_cop('Style/For')
expected_part = (27..source.size).to_a
expect(for_disabled_lines & expected_part).to eq(expected_part)
end
it 'just ignores unpaired enabling directives' do
void_disabled_lines = disabled_lines_of_cop('Lint/Void')
expected_part = (25..source.size).to_a
expect(void_disabled_lines & expected_part).to be_empty
end
it 'supports disabling single line with a directive at end of line' do
eval_disabled_lines = disabled_lines_of_cop('Security/Eval')
expect(eval_disabled_lines).to include(12)
expect(eval_disabled_lines).not_to include(13)
end
it 'handles indented single line' do
line_length_disabled_lines = disabled_lines_of_cop('Layout/LineLength')
expect(line_length_disabled_lines).to include(16)
expect(line_length_disabled_lines).not_to include(18)
end
it 'does not confuse a comment directive embedded in a string literal with a real comment' do
loop_disabled_lines = disabled_lines_of_cop('Loop')
expect(loop_disabled_lines).not_to include(20)
end
it 'supports disabling all cops except Lint/RedundantCopDisableDirective and Lint/Syntax with keyword all' do
expected_part = (7..8).to_a
excluded = [RuboCop::Cop::Lint::RedundantCopDisableDirective, RuboCop::Cop::Lint::Syntax]
cops = RuboCop::Cop::Registry.all - excluded
cops.each do |cop|
disabled_lines = disabled_lines_of_cop(cop)
expect(disabled_lines & expected_part).to eq(expected_part)
end
end
it 'does not confuse a cop name including "all" with all cops' do
alias_disabled_lines = disabled_lines_of_cop('Alias')
expect(alias_disabled_lines).not_to include(23)
end
it 'can handle double disable of one cop' do
expect(disabled_lines_of_cop('Style/ClassVars')).to eq([7, 8, 9] + (31..source.size).to_a)
end
it 'supports disabling cops with multiple uppercase letters' do
expect(disabled_lines_of_cop('RSpec/Example')).to include(47)
end
it 'supports disabling cops with numbers in their name' do
expect(disabled_lines_of_cop('Custom2/Number9')).to include(48)
end
it 'supports disabling cops on a comment line with an EOL comment' do
expect(disabled_lines_of_cop('Layout/LeadingCommentSpace')).to eq([7, 8, 9, 50])
end
end
describe '#cop_disabled_line_ranges' do
subject(:range) { comment_config.cop_disabled_line_ranges }
let(:source) do
<<~RUBY
# rubocop:disable Metrics/MethodLength with a comment why
def some_method
puts 'foo'
end
# rubocop:enable Metrics/MethodLength
code = 'This is evil.'
eval(code) # rubocop:disable Security/Eval
puts 'This is not evil.'
RUBY
end
it 'collects line ranges by disabled cops' do
expect(range).to eq({ 'Metrics/MethodLength' => [1..5], 'Security/Eval' => [8..8] })
end
end
describe '#extra_enabled_comments' do
subject(:extra) { comment_config.extra_enabled_comments }
let(:source) do
<<~RUBY
# rubocop:enable Metrics/MethodLength, Security/Eval
def some_method
puts 'foo'
end
RUBY
end
it 'has keys as instances of Parser::Source::Comment for extra enabled comments' do
key = extra.keys.first
expect(key).to be_a(Parser::Source::Comment)
expect(key.text).to eq '# rubocop:enable Metrics/MethodLength, Security/Eval'
end
it 'has values as arrays of extra enabled cops' do
expect(extra.values.first).to eq ['Metrics/MethodLength', 'Security/Eval']
end
end
describe 'comment_only_line?' do
let(:source) do
<<~RUBY
# rubocop:disable Metrics/MethodLength 01
def some_method
puts 'foo'
end
# rubocop:enable Metrics/MethodLength 05
code = 'This is evil.'
eval(code) # rubocop:disable Security/Eval
RUBY
end
context 'when line contains only comment' do
[1, 5].each do |line_number|
it 'returns true' do
expect(comment_config).to be_comment_only_line(line_number)
end
end
end
context 'when line is empty' do
[6].each do |line_number|
it 'returns true' do
expect(comment_config).to be_comment_only_line(line_number)
end
end
end
context 'when line contains only code' do
[2, 3, 4, 7].each do |line_number|
it 'returns false' do
expect(comment_config).not_to be_comment_only_line(line_number)
end
end
end
context 'when line contains code and comment' do
[8].each do |line_number|
it 'returns false' do
expect(comment_config).not_to be_comment_only_line(line_number)
end
end
end
end
describe 'push/pop directives' do
def disabled_lines_of_cop(cop)
(1..source.size).each_with_object([]) do |line_number, disabled_lines|
enabled = comment_config.cop_enabled_at_line?(cop, line_number)
disabled_lines << line_number unless enabled
end
end
context 'temporarily disable a cop for a problematic block' do
let(:source) do
<<~RUBY
def process_data(input)
result = input.upcase
# rubocop:push
# rubocop:disable Style/GuardClause
if result.present?
return result.strip
end
# rubocop:pop
nil
end
RUBY
end
it 'disables GuardClause only inside push/pop block' do
disabled = disabled_lines_of_cop('Style/GuardClause')
# Lines 4-7 should be disabled (push to pop)
expect(disabled).to include(4, 5, 6, 7)
# Lines outside push/pop should be enabled
expect(disabled).not_to include(1, 2, 3, 8, 9, 10)
end
end
context 'enable a disabled cop temporarily' do
let(:source) do
<<~RUBY
# rubocop:disable Metrics/MethodLength
def long_method
line1
line2
# rubocop:push
# rubocop:enable Metrics/MethodLength
def short_method
line3
end
# rubocop:pop
line4
line5
end
RUBY
end
it 'enables MethodLength only inside push/pop block' do
disabled = disabled_lines_of_cop('Metrics/MethodLength')
# Lines 1-6 should be disabled (before and including enable)
expect(disabled).to include(1, 2, 3, 4, 5, 6)
# Lines 7-9 should be enabled (after enable, inside push/pop)
expect(disabled).not_to include(7, 8, 9)
# Lines 10-13 should be disabled (after pop restores state)
expect(disabled).to include(10, 11, 12, 13)
end
end
context 'multiple cops disabled then one enabled in push/pop' do
let(:source) do
<<~RUBY
# rubocop:disable Style/For, Style/Not
for x in [1, 2, 3]
not x.nil?
end
# rubocop:push
# rubocop:enable Style/For
for y in [4, 5, 6]
not y.nil?
end
# rubocop:pop
for z in [7, 8, 9]
not z.nil?
end
RUBY
end
it 'enables only Style/For inside push/pop, keeps Style/Not disabled' do
for_disabled = disabled_lines_of_cop('Style/For')
not_disabled = disabled_lines_of_cop('Style/Not')
# Style/For: disabled 1-6 (including enable line), enabled 7-9, disabled 10-13
expect(for_disabled).to include(1, 2, 3, 4, 5, 6)
expect(for_disabled).not_to include(7, 8, 9)
expect(for_disabled).to include(10, 11, 12, 13)
# Style/Not: disabled everywhere (never enabled)
expect(not_disabled).to include(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
end
end
context 'disable new cop in push/pop, original stays enabled' do
let(:source) do
<<~RUBY
def process
x = 1
y = 2
# rubocop:push
# rubocop:disable Style/NumericPredicate
if x.size == 0
puts 'empty'
end
# rubocop:pop
if y.size == 0
puts 'also empty'
end
end
RUBY
end
it 'disables NumericPredicate only inside push/pop' do
disabled = disabled_lines_of_cop('Style/NumericPredicate')
# Lines 5-8 should be disabled (inside push/pop)
expect(disabled).to include(5, 6, 7, 8)
# Lines outside should be enabled
expect(disabled).not_to include(1, 2, 3, 4, 9, 10, 11, 12)
end
end
context 'nested push/pop for complex refactoring' do
let(:source) do
<<~RUBY
# rubocop:disable Metrics/MethodLength
def complex_method
step1
# rubocop:push
# rubocop:enable Metrics/MethodLength
# rubocop:disable Style/GuardClause
def helper_method
# rubocop:push
# rubocop:enable Style/GuardClause
if condition
return value
end
# rubocop:pop
other_code
end
# rubocop:pop
step2
end
RUBY
end
it 'handles nested enable/disable correctly' do
method_length_disabled = disabled_lines_of_cop('Metrics/MethodLength')
guard_clause_disabled = disabled_lines_of_cop('Style/GuardClause')
# Metrics/MethodLength: disabled 1-5 (including enable line),
# enabled 6-15 (after enable), disabled 16-18 (after pop)
expect(method_length_disabled).to include(1, 2, 3, 4, 5)
expect(method_length_disabled).not_to include(6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
expect(method_length_disabled).to include(16, 17, 18)
# Style/GuardClause: enabled 1-5, disabled 6-9 (including enable line),
# enabled 10-12, disabled 13-15 (after nested pop), enabled 16-18
expect(guard_clause_disabled).not_to include(1, 2, 3, 4, 5)
expect(guard_clause_disabled).to include(6, 7, 8, 9)
expect(guard_clause_disabled).not_to include(10, 11, 12)
expect(guard_clause_disabled).to include(13, 14, 15)
expect(guard_clause_disabled).not_to include(16, 17, 18)
end
end
context 'disable cop for multi-line assignment with push/pop' do
let(:source) do
<<~RUBY
def configure(stage)
# rubocop:push
# rubocop:disable Layout/SpaceAroundMethodCallOperator
self.stage =
if 'macro' .start_with? stage; Langeod::MACRO
elsif 'dynamic'.start_with? stage; Langeod::DYNAMIC
elsif 'static' .start_with? stage; Langeod::STATIC
else raise ArgumentError, "invalid stage: \#{stage}"
end
# rubocop:pop
validate_stage
end
RUBY
end
it 'disables SpaceAroundMethodCallOperator only inside push/pop block' do
disabled = disabled_lines_of_cop('Layout/SpaceAroundMethodCallOperator')
# Lines 3-9 should be disabled (from disable to before pop)
expect(disabled).to include(3, 4, 5, 6, 7, 8, 9)
# Lines outside push/pop should be enabled
expect(disabled).not_to include(1, 2, 10, 11, 12)
end
end
context 'push with inline arguments: disable cop temporarily' do
let(:source) do
<<~RUBY
def process_data(input)
result = input.upcase
# rubocop:push -Style/GuardClause
if result.present?
return result.strip
end
# rubocop:pop
nil
end
RUBY
end
it 'disables GuardClause only inside push/pop block' do
disabled = disabled_lines_of_cop('Style/GuardClause')
# Lines 3-6 should be disabled (from push line to before pop)
expect(disabled).to include(3, 4, 5, 6)
# Lines outside push/pop should be enabled
expect(disabled).not_to include(1, 2, 7, 8, 9)
end
end
context 'push with inline arguments: enable cop temporarily' do
let(:source) do
<<~RUBY
# rubocop:disable Metrics/MethodLength
def long_method
line1
line2
# rubocop:push +Metrics/MethodLength
def short_method
line3
end
# rubocop:pop
line4
line5
end
RUBY
end
it 'enables MethodLength only inside push/pop block' do
disabled = disabled_lines_of_cop('Metrics/MethodLength')
# Lines 1-4 should be disabled (before push)
expect(disabled).to include(1, 2, 3, 4)
# Lines 6-8 should be enabled (after +enable, inside push/pop)
expect(disabled).not_to include(6, 7, 8)
# Lines 10-12 should be disabled (after pop restores state)
expect(disabled).to include(10, 11, 12)
end
end
context 'push with multiple inline arguments' do
let(:source) do
<<~RUBY
# rubocop:disable Style/For, Style/Not
for x in [1, 2, 3]
not x.nil?
end
# rubocop:push +Style/For -Style/GuardClause
for y in [4, 5, 6]
not y.nil?
if true
return 1
end
end
# rubocop:pop
for z in [7, 8, 9]
not z.nil?
end
RUBY
end
it 'enables Style/For and disables Style/GuardClause inside push/pop' do
for_disabled = disabled_lines_of_cop('Style/For')
not_disabled = disabled_lines_of_cop('Style/Not')
guard_disabled = disabled_lines_of_cop('Style/GuardClause')
# Style/For: disabled 1-5, enabled 5-11, disabled 12-16
expect(for_disabled).to include(1, 2, 3, 4, 5)
expect(for_disabled).not_to include(6, 7, 8, 9, 10, 11)
expect(for_disabled).to include(12, 13, 14, 15, 16)
# Style/Not: disabled everywhere (never enabled)
expect(not_disabled).to include(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
# Style/GuardClause: only disabled inside push/pop (5-11)
expect(guard_disabled).to include(5, 6, 7, 8, 9, 10, 11)
expect(guard_disabled).not_to include(1, 2, 3, 4, 12, 13, 14, 15, 16)
end
end
context 'push with arguments should work without separate enable/disable lines' do
let(:source) do
<<~RUBY
def process
x = 1
y = 2
# rubocop:push -Style/NumericPredicate +Metrics/MethodLength
if x.size == 0
puts 'empty'
end
if y.size == 1
puts 'one'
end
# rubocop:pop
if y.size == 2
puts 'two'
end
end
RUBY
end
it 'disables NumericPredicate and enables MethodLength only inside push/pop' do
numeric_disabled = disabled_lines_of_cop('Style/NumericPredicate')
method_disabled = disabled_lines_of_cop('Metrics/MethodLength')
# Style/NumericPredicate: disabled 4-10
expect(numeric_disabled).to include(4, 5, 6, 7, 8, 9, 10)
expect(numeric_disabled).not_to include(1, 2, 3, 11, 12, 13, 14, 15, 16)
# Metrics/MethodLength: enabled 4-10
expect(method_disabled).not_to include(4, 5, 6, 7, 8, 9, 10)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/directive_comment_spec.rb | spec/rubocop/directive_comment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::DirectiveComment do
let(:directive_comment) { described_class.new(comment, cop_registry) }
let(:comment) { instance_double(Parser::Source::Comment, text: text) }
let(:cop_registry) do
instance_double(RuboCop::Cop::Registry, names: all_cop_names, department?: department?)
end
let(:text) { '#rubocop:enable all' }
let(:all_cop_names) { %w[] }
let(:department?) { false }
describe '.before_comment' do
subject { described_class.before_comment(text) }
context 'when line has code' do
let(:text) { 'def foo # rubocop:disable all' }
it { is_expected.to eq('def foo ') }
end
context 'when line has NO code' do
let(:text) { '# rubocop:disable all' }
it { is_expected.to eq('') }
end
end
describe '#match?' do
subject { directive_comment.match?(cop_names) }
let(:text) { '#rubocop:enable Metrics/AbcSize, Metrics/PerceivedComplexity, Style/Not' }
context 'when there are no cop names' do
let(:cop_names) { [] }
it { is_expected.to be(false) }
end
context 'when cop names are same as in the comment' do
let(:cop_names) { %w[Metrics/AbcSize Metrics/PerceivedComplexity Style/Not] }
it { is_expected.to be(true) }
end
context 'when cop names are same but in a different order' do
let(:cop_names) { %w[Style/Not Metrics/AbcSize Metrics/PerceivedComplexity] }
it { is_expected.to be(true) }
end
context 'when cop names are subset of names' do
let(:cop_names) { %w[Metrics/AbcSize Style/Not] }
it { is_expected.to be(false) }
end
context 'when cop names are superset of names' do
let(:cop_names) { %w[Lint/Void Metrics/AbcSize Metrics/PerceivedComplexity Style/Not] }
it { is_expected.to be(false) }
end
context 'when cop names are same but have duplicated names' do
let(:cop_names) { %w[Metrics/AbcSize Metrics/AbcSize Metrics/PerceivedComplexity Style/Not] }
it { is_expected.to be(true) }
end
context 'when disabled all cops' do
let(:text) { '#rubocop:enable all' }
let(:cop_names) { %w[all] }
it { is_expected.to be(true) }
end
end
describe '#match_captures' do
subject { directive_comment.match_captures }
context 'when disable' do
let(:text) { '# rubocop:disable all' }
it { is_expected.to eq(%w[disable all]) }
end
context 'when enable' do
let(:text) { '# rubocop:enable Foo/Bar' }
it { is_expected.to eq(['enable', 'Foo/Bar']) }
end
context 'when todo' do
let(:text) { '# rubocop:todo all' }
it { is_expected.to eq(%w[todo all]) }
end
context 'when typo' do
let(:text) { '# rudocop:todo Dig/ThisMine' }
it { is_expected.to be_nil }
end
end
describe '#single_line?' do
subject { directive_comment.single_line? }
context 'when relates to single line' do
let(:text) { 'def foo # rubocop:disable all' }
it { is_expected.to be(true) }
end
context 'when does NOT relate to single line' do
let(:text) { '# rubocop:disable all' }
it { is_expected.to be(false) }
end
end
describe '#disabled?' do
subject { directive_comment.disabled? }
context 'when disable' do
let(:text) { '# rubocop:disable all' }
it { is_expected.to be(true) }
end
context 'when enable' do
let(:text) { '# rubocop:enable Foo/Bar' }
it { is_expected.to be(false) }
end
context 'when todo' do
let(:text) { '# rubocop:todo all' }
it { is_expected.to be(true) }
end
end
describe '#enabled?' do
subject { directive_comment.enabled? }
context 'when disable' do
let(:text) { '# rubocop:disable all' }
it { is_expected.to be(false) }
end
context 'when enable' do
let(:text) { '# rubocop:enable Foo/Bar' }
it { is_expected.to be(true) }
end
context 'when todo' do
let(:text) { '# rubocop:todo all' }
it { is_expected.to be(false) }
end
end
describe '#all_cops?' do
subject { directive_comment.all_cops? }
context 'when mentioned all' do
let(:text) { '# rubocop:disable all' }
it { is_expected.to be(true) }
end
context 'when mentioned specific cops' do
let(:text) { '# rubocop:enable Foo/Bar' }
it { is_expected.to be(false) }
end
end
describe '#cop_names' do
subject { directive_comment.cop_names }
context 'when only cop specified' do
let(:text) { '#rubocop:enable Foo/Bar' }
it { is_expected.to eq(%w[Foo/Bar]) }
end
context 'when all cops mentioned' do
let(:text) { '#rubocop:enable all' }
let(:all_cop_names) { %w[all_names Lint/RedundantCopDisableDirective] }
it { is_expected.to eq(%w[all_names]) }
end
context 'when only department specified' do
let(:text) { '#rubocop:enable Foo' }
let(:department?) { true }
before do
allow(cop_registry).to receive(:names_for_department)
.with('Foo').and_return(%w[Foo/Bar Foo/Baz])
end
it { is_expected.to eq(%w[Foo/Bar Foo/Baz]) }
end
context 'when couple departments specified' do
let(:text) { '#rubocop:enable Foo, Baz' }
let(:department?) { true }
before do
allow(cop_registry).to receive(:names_for_department).with('Baz').and_return(%w[Baz/Bar])
allow(cop_registry).to receive(:names_for_department)
.with('Foo').and_return(%w[Foo/Bar Foo/Baz])
end
it { is_expected.to eq(%w[Foo/Bar Foo/Baz Baz/Bar]) }
end
context 'when department and cops specified' do
let(:text) { '#rubocop:enable Foo, Baz/Cop' }
before do
allow(cop_registry).to receive(:department?).with('Foo').and_return(true)
allow(cop_registry).to receive(:names_for_department)
.with('Foo').and_return(%w[Foo/Bar Foo/Baz])
end
it { is_expected.to eq(%w[Foo/Bar Foo/Baz Baz/Cop]) }
end
context 'when redundant directive cop department specified' do
let(:text) { '#rubocop:enable Lint' }
let(:department?) { true }
before do
allow(cop_registry).to receive(:names_for_department)
.with('Lint').and_return(%w[Lint/One Lint/Two Lint/RedundantCopDisableDirective])
end
it { is_expected.to eq(%w[Lint/One Lint/Two]) }
end
end
describe '#department_names' do
subject { directive_comment.department_names }
context 'when only cop specified' do
let(:text) { '#rubocop:enable Foo/Bar' }
it { is_expected.to eq([]) }
end
context 'when all cops mentioned' do
let(:text) { '#rubocop:enable all' }
it { is_expected.to eq([]) }
end
context 'when only department specified' do
let(:text) { '#rubocop:enable Foo' }
let(:department?) { true }
it { is_expected.to eq(%w[Foo]) }
end
context 'when couple departments specified' do
let(:text) { '#rubocop:enable Foo, Baz' }
let(:department?) { true }
it { is_expected.to eq(%w[Foo Baz]) }
end
context 'when department and cops specified' do
let(:text) { '#rubocop:enable Foo, Baz/Cop' }
before do
allow(cop_registry).to receive(:department?).with('Foo').and_return(true)
end
it { is_expected.to eq(%w[Foo]) }
end
end
describe '#line_number' do
let(:source_range) do
instance_double(Parser::Source::Range, line: 1)
end
before { allow(comment).to receive(:source_range).and_return(source_range) }
it 'returns line number for directive' do
expect(directive_comment.line_number).to eq(1)
end
end
describe '#enabled_all?' do
subject { directive_comment.enabled_all? }
context 'when enabled all cops' do
let(:text) { 'def foo # rubocop:enable all' }
it { is_expected.to be(true) }
end
context 'when enabled specific cops' do
let(:text) { '# rubocop:enable Foo/Bar' }
it { is_expected.to be(false) }
end
context 'when disabled all cops' do
let(:text) { '# rubocop:disable all' }
it { is_expected.to be(false) }
end
context 'when disabled specific cops' do
let(:text) { '# rubocop:disable Foo/Bar' }
it { is_expected.to be(false) }
end
end
describe '#disabled_all?' do
subject { directive_comment.disabled_all? }
context 'when enabled all cops' do
let(:text) { 'def foo # rubocop:enable all' }
it { is_expected.to be(false) }
end
context 'when enabled specific cops' do
let(:text) { '# rubocop:enable Foo/Bar' }
it { is_expected.to be(false) }
end
context 'when disabled all cops' do
let(:text) { '# rubocop:disable all' }
it { is_expected.to be(true) }
end
context 'when disabled specific cops' do
let(:text) { '# rubocop:disable Foo/Bar' }
it { is_expected.to be(false) }
end
end
describe '#directive_count' do
subject { directive_comment.directive_count }
context 'when few cops used' do
let(:text) { '# rubocop:enable Foo/Bar, Foo/Baz' }
it { is_expected.to eq(2) }
end
context 'when few department used' do
let(:text) { '# rubocop:enable Foo, Bar, Baz' }
it { is_expected.to eq(3) }
end
context 'when cops and departments used' do
let(:text) { '# rubocop:enable Foo/Bar, Foo/Baz, Bar, Baz' }
it { is_expected.to eq(4) }
end
end
describe '#in_directive_department?' do
subject { directive_comment.in_directive_department?('Foo/Bar') }
context 'when cop department disabled' do
let(:text) { '# rubocop:enable Foo' }
let(:department?) { true }
it { is_expected.to be(true) }
end
context 'when another department disabled' do
let(:text) { '# rubocop:enable Bar' }
let(:department?) { true }
it { is_expected.to be(false) }
end
context 'when cop disabled' do
let(:text) { '# rubocop:enable Foo/Bar' }
it { is_expected.to be(false) }
end
end
describe '#overridden_by_department?' do
subject { directive_comment.overridden_by_department?('Foo/Bar') }
before do
allow(cop_registry).to receive(:department?).with('Foo').and_return(true)
end
context "when cop is overridden by it's department" do
let(:text) { '# rubocop:enable Foo, Foo/Bar' }
it { is_expected.to be(true) }
end
context "when cop is not overridden by it's department" do
let(:text) { '# rubocop:enable Bar, Foo/Bar' }
it { is_expected.to be(false) }
end
context 'when there are no departments' do
let(:text) { '# rubocop:enable Foo/Bar' }
it { is_expected.to be(false) }
end
context 'when there are no cops' do
let(:text) { '# rubocop:enable Foo' }
it { is_expected.to be(false) }
end
end
describe '#raw_cop_names' do
subject { directive_comment.raw_cop_names }
context 'when there are departments' do
let(:text) { '# rubocop:enable Style, Lint/Void' }
it { is_expected.to eq(%w[Style Lint/Void]) }
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/config_store_spec.rb | spec/rubocop/config_store_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::ConfigStore do
subject(:config_store) { described_class.new }
before do
allow(RuboCop::ConfigLoader).to receive(:configuration_file_for) do |arg|
# File tree:
# file1
# dir/.rubocop.yml
# dir/file2
# dir/subdir/file3
"#{arg.include?('dir') ? 'dir' : '.'}/.rubocop.yml"
end
allow(RuboCop::ConfigLoader).to receive(:configuration_from_file) { |arg| arg }
allow(RuboCop::ConfigLoader).to receive(:load_file) { |arg| RuboCop::Config.new(arg) }
allow(RuboCop::ConfigLoader)
.to receive(:merge_with_default) { |config| "merged #{config.to_h}" }
allow(RuboCop::ConfigLoader).to receive(:default_configuration).and_return('default config')
end
describe '.for' do
it 'always uses config specified in command line' do
config = { options_config: true }
config_store.options_config = config
expect(config_store.for('file1')).to eq("merged #{config}")
end
context 'when no config specified in command line' do
it 'gets config path and config from cache if available' do
expect(RuboCop::ConfigLoader).to receive(:configuration_file_for).with('dir').once
expect(RuboCop::ConfigLoader).to receive(:configuration_file_for).with('dir/subdir').once
# The stub returns the same config path for dir and dir/subdir.
expect(RuboCop::ConfigLoader)
.to receive(:configuration_from_file)
.with('dir/.rubocop.yml', check: true).once
config_store.for('dir/file2')
config_store.for('dir/file2')
config_store.for('dir/subdir/file3')
end
it 'searches for config path if not available in cache' do
expect(RuboCop::ConfigLoader).to receive(:configuration_file_for).once
expect(RuboCop::ConfigLoader).to receive(:configuration_from_file).once
config_store.for('file1')
end
context 'when --force-default-config option is specified' do
it 'uses default config without searching for config path' do
expect(RuboCop::ConfigLoader).not_to receive(:configuration_file_for)
expect(RuboCop::ConfigLoader).not_to receive(:configuration_from_file)
config_store.force_default_config!
expect(config_store.for('file1')).to eq('default config')
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/plugin_spec.rb | spec/rubocop/plugin_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Plugin do
describe '.plugin_capable?' do
subject { described_class.plugin_capable?(feature) }
context 'when feature is a built-in plugin' do
let(:feature) { 'rubocop/cop/internal_affairs' }
it { is_expected.to be(true) }
end
context 'when feature is an unknown extension plugin' do
let(:feature) { 'unknown_extension' }
it { is_expected.to be(false) }
end
end
describe '.integrate_plugins' do
before { described_class.integrate_plugins(rubocop_config, plugins) }
let(:rubocop_config) { RuboCop::Config.new }
context 'when using plugin' do
let(:plugins) { ['rubocop/cop/internal_affairs'] }
it 'integrates base cops' do
expect(rubocop_config.to_h['Style/HashSyntax']['SupportedStyles']).to eq(
%w[ruby19 hash_rockets no_mixed_keys ruby19_no_mixed_keys]
)
end
it 'integrates plugin cops' do
expect(rubocop_config.to_h['InternalAffairs/CopDescription']).to eq(
{ 'Include' => ['lib/rubocop/cop/**/*.rb'] }
)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/lockfile_spec.rb | spec/rubocop/lockfile_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Lockfile, :isolated_environment do
include FileHelper
subject { described_class.new }
let(:lockfile) do
create_file('Gemfile.lock', <<~LOCKFILE)
GEM
specs:
rake (13.0.1)
rspec (3.9.0)
dep (1.0.0)
dep2 (~> 1.0)
dep2 (1.0.0)
dep3 (~> 1.0)
PLATFORMS
ruby
DEPENDENCIES
dep (~> 1.0.0)
rake (~> 13.0)
rspec (~> 3.7)
LOCKFILE
end
before do
allow(Bundler).to receive(:default_lockfile)
.and_return(lockfile ? Pathname.new(lockfile) : nil)
end
shared_examples 'error states' do
context 'when bundler is not loaded' do
before { hide_const('Bundler') }
it { is_expected.to eq([]) }
end
context 'when there is no lockfile' do
let(:lockfile) { nil }
it { is_expected.to eq([]) }
end
context 'when there is a garbage lockfile' do
let(:lockfile) do
create_file('Gemfile.lock', <<~LOCKFILE)
<<<<<<<
LOCKFILE
end
it { is_expected.to eq([]) }
end
context 'when there is a gemfile without lockfile' do
let(:lockfile) { nil }
before do
allow(Bundler).to receive(:default_lockfile).and_return('Gemfile.lock')
create_file('Gemfile', <<~GEMFILE)
gem 'rubocop', '~> 1.65.0'
GEMFILE
end
it { is_expected.to eq([]) }
end
end
describe '#dependencies' do
subject { super().dependencies }
let(:names) { subject.map(&:name) }
it_behaves_like 'error states'
it 'returns all the dependencies' do
expect(names).to contain_exactly('dep', 'rake', 'rspec')
end
context 'when there is an empty lockfile' do
let(:lockfile) { create_empty_file('Gemfile.lock') }
it { is_expected.to eq([]) }
end
end
describe '#gems' do
subject { super().gems }
let(:names) { subject.map(&:name) }
it_behaves_like 'error states'
it 'returns all the dependencies' do
expect(names).to contain_exactly('dep', 'dep2', 'dep3', 'rake', 'rspec')
end
context 'when there is an empty lockfile' do
let(:lockfile) { create_empty_file('Gemfile.lock') }
it { is_expected.to eq([]) }
end
end
describe '#includes_gem?' do
subject { super().includes_gem?(name) }
context 'for an included dependency' do
let(:name) { 'rake' }
it { is_expected.to be(true) }
end
context 'for an included gem' do
let(:name) { 'dep2' }
it { is_expected.to be(true) }
end
context 'for an excluded gem' do
let(:name) { 'other' }
it { is_expected.to be(false) }
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/config_loader_spec.rb | spec/rubocop/config_loader_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::ConfigLoader do
include FileHelper
include_context 'cli spec behavior'
before do
described_class.debug = true
# Force reload of default configuration
described_class.default_configuration = nil
RuboCop::ConfigFinder.project_root = nil
end
after do
described_class.debug = false
# Remove custom configuration
described_class.default_configuration = nil
RuboCop::ConfigFinder.project_root = nil
end
let(:default_config) { described_class.default_configuration }
describe '.configuration_file_for', :isolated_environment do
subject(:configuration_file_for) { described_class.configuration_file_for(dir_path) }
context 'when no config file exists in ancestor directories' do
let(:dir_path) { 'dir' }
before { create_empty_file('dir/example.rb') }
context 'but a config file exists in .config/.rubocop.yml of the project root' do
before do
create_empty_file('Gemfile')
create_empty_file('.config/.rubocop.yml')
end
it 'returns the path to the file in .config directory' do
expect(configuration_file_for).to end_with('.config/.rubocop.yml')
end
end
context 'but a config file exists in both .config/.rubocop.yml of the project root and home directory' do
before do
create_empty_file('Gemfile')
create_empty_file('.config/.rubocop.yml')
create_empty_file('~/.rubocop.yml')
end
it 'returns the path to the file in .config directory' do
expect(configuration_file_for).to end_with('.config/.rubocop.yml')
end
end
context 'but a config file exists in .config/rubocop/config.yml of the project root' do
before do
create_empty_file('Gemfile')
create_empty_file('.config/rubocop/config.yml')
end
it 'returns the path to the file in .config/rubocop directory' do
expect(configuration_file_for).to end_with('.config/rubocop/config.yml')
end
end
context 'but a config file exists in both .config/.rubocop.yml and .config/rubocop/config.yml of the project root' do
before do
create_empty_file('Gemfile')
create_empty_file('.config/.rubocop.yml')
create_empty_file('.config/rubocop/config.yml')
end
it 'returns the path to the file in .config directory' do
expect(configuration_file_for).to end_with('.config/.rubocop.yml')
end
end
context 'but a config file exists in both .config//rubocop/config.yml of the project root and home directory' do
before do
create_empty_file('Gemfile')
create_empty_file('.config/rubocop/config.yml')
create_empty_file('~/.rubocop.yml')
end
it 'returns the path to the file in .config/rubocop directory' do
expect(configuration_file_for).to end_with('.config/rubocop/config.yml')
end
end
context 'but a config file exists in home directory' do
before { create_empty_file('~/.rubocop.yml') }
it 'returns the path to the file in home directory' do
expect(configuration_file_for).to end_with('home/.rubocop.yml')
end
end
context 'but a config file exists in default XDG config directory' do
before { create_empty_file('~/.config/rubocop/config.yml') }
it 'returns the path to the file in XDG directory' do
expect(configuration_file_for).to end_with('home/.config/rubocop/config.yml')
end
end
context 'but a config file exists in a custom XDG config directory' do
before do
ENV['XDG_CONFIG_HOME'] = '~/xdg-stuff'
create_empty_file('~/xdg-stuff/rubocop/config.yml')
end
it 'returns the path to the file in XDG directory' do
expect(configuration_file_for).to end_with('home/xdg-stuff/rubocop/config.yml')
end
end
context 'but a config file exists in both home and XDG directories' do
before do
create_empty_file('~/.config/rubocop/config.yml')
create_empty_file('~/.rubocop.yml')
end
it 'returns the path to the file in home directory' do
expect(configuration_file_for).to end_with('home/.rubocop.yml')
end
end
context 'and no config file exists in home or XDG directory' do
it 'falls back to the provided default file' do
expect(configuration_file_for).to end_with('config/default.yml')
end
end
context 'and ENV has no `HOME` defined' do
before { ENV.delete 'HOME' }
it 'falls back to the provided default file' do
expect(configuration_file_for).to end_with('config/default.yml')
end
end
end
context 'when there is a spurious rubocop config outside of the project', root: 'dir' do
let(:dir_path) { 'dir' }
before do
# Force reload of project root
RuboCop::ConfigFinder.project_root = nil
create_empty_file('Gemfile')
create_empty_file('../.rubocop.yml')
end
after do
# Don't leak project root change
RuboCop::ConfigFinder.project_root = nil
end
it 'ignores the spurious config and falls back to the provided default file if run from the project' do
expect(configuration_file_for).to end_with('config/default.yml')
end
end
context 'when a config file exists in the parent directory' do
let(:dir_path) { 'dir' }
before do
create_empty_file('dir/example.rb')
create_empty_file('.rubocop.yml')
end
it 'returns the path to that configuration file' do
expect(configuration_file_for).to end_with('work/.rubocop.yml')
end
end
context 'when multiple config files exist in ancestor directories' do
let(:dir_path) { 'dir' }
before do
create_empty_file('dir/example.rb')
create_empty_file('dir/.rubocop.yml')
create_empty_file('.rubocop.yml')
end
it 'prefers closer config file' do
expect(configuration_file_for).to end_with('dir/.rubocop.yml')
end
end
end
describe '.configuration_from_file', :isolated_environment do
subject(:configuration_from_file) { described_class.configuration_from_file(file_path) }
context 'with any config file' do
let(:file_path) { '.rubocop.yml' }
before do
create_file(file_path, <<~YAML)
Style/Encoding:
Enabled: false
YAML
end
it 'returns a configuration inheriting from default.yml' do
config = default_config['Style/Encoding'].dup
config['Enabled'] = false
expect(configuration_from_file.to_h)
.to eql(default_config.merge('Style/Encoding' => config))
end
end
context 'when multiple config files exist in ancestor directories' do
let(:file_path) { 'dir/.rubocop.yml' }
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
Exclude:
- vendor/**
YAML
create_file(file_path, <<~YAML)
AllCops:
Exclude: []
YAML
end
it 'gets AllCops/Exclude from the highest directory level' do
excludes = configuration_from_file['AllCops']['Exclude']
expect(excludes).to eq([File.expand_path('vendor/**')])
end
context 'and there is a personal config file in the home folder' do
before do
create_file('~/.rubocop.yml', <<~YAML)
AllCops:
Exclude:
- tmp/**
YAML
end
it 'ignores personal AllCops/Exclude' do
excludes = configuration_from_file['AllCops']['Exclude']
expect(excludes).to eq([File.expand_path('vendor/**')])
end
end
end
context 'when configuration has a custom name' do
let(:file_path) { '.custom_rubocop.yml' }
before do
create_file(file_path, <<~YAML)
AllCops:
Exclude:
- vendor/**
YAML
end
context 'and there is a personal config file in the home folder' do
before do
create_file('~/.rubocop.yml', <<~YAML)
AllCops:
Exclude:
- tmp/**
YAML
end
it 'ignores personal AllCops/Exclude' do
excludes = configuration_from_file['AllCops']['Exclude']
expect(excludes).to eq([File.expand_path('vendor/**')])
end
end
end
context 'when project has a Gemfile', :project_inside_home do
let(:file_path) { '.rubocop.yml' }
before do
create_empty_file('Gemfile')
create_file(file_path, <<~YAML)
AllCops:
Exclude:
- vendor/**
YAML
end
context 'and there is a personal config file in the home folder' do
before do
create_file('~/.rubocop.yml', <<~YAML)
AllCops:
Exclude:
- tmp/**
YAML
end
it 'ignores personal AllCops/Exclude' do
excludes = configuration_from_file['AllCops']['Exclude']
expect(excludes).to eq([File.expand_path('vendor/**')])
end
end
end
context 'when a parent file specifies DisabledByDefault: true' do
let(:file_path) { '.rubocop.yml' }
before do
create_file('disable.yml', <<~YAML)
AllCops:
DisabledByDefault: true
YAML
create_file(file_path, ['inherit_from: disable.yml'])
end
it 'disables cops by default' do
cop_options = configuration_from_file['Style/Alias']
expect(cop_options.fetch('Enabled')).to be(false)
end
end
context 'when a file inherits from a parent file' do
let(:file_path) { 'dir/.rubocop.yml' }
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
Exclude:
- vendor/**
- !ruby/regexp /[A-Z]/
Style/StringLiterals:
Include:
- dir/**/*.rb
YAML
create_file(file_path, ['inherit_from: ../.rubocop.yml'])
end
it 'gets an absolute AllCops/Exclude' do
excludes = configuration_from_file['AllCops']['Exclude']
expect(excludes).to eq([File.expand_path('vendor/**'), /[A-Z]/])
end
it 'gets an Include that is relative to the subdirectory' do
expect(configuration_from_file['Style/StringLiterals']['Include']).to eq(['**/*.rb'])
end
it 'ignores parent AllCops/Exclude if ignore_parent_exclusion is true' do
sub_file_path = 'vendor/.rubocop.yml'
create_file(sub_file_path, <<~YAML)
AllCops:
Exclude:
- 'foo'
YAML
# dup the class so that setting ignore_parent_exclusion doesn't
# interfere with other specs
config_loader = described_class.dup
config_loader.ignore_parent_exclusion = true
configuration = config_loader.configuration_from_file(sub_file_path)
excludes = configuration['AllCops']['Exclude']
expect(excludes).not_to include(File.expand_path('vendor/**'))
expect(excludes).to include(File.expand_path('vendor/foo'))
end
end
context 'when a file inherits from an empty parent file' do
let(:file_path) { 'dir/.rubocop.yml' }
before do
create_file('.rubocop.yml', [''])
create_file(file_path, ['inherit_from: ../.rubocop.yml'])
end
it 'does not fail to load' do
expect { configuration_from_file }.not_to raise_error
end
end
context 'when a file inherits from a sibling file' do
let(:file_path) { 'dir/.rubocop.yml' }
before do
create_file('src/.rubocop.yml', <<~YAML)
AllCops:
Exclude:
- vendor/**
Style/StringLiterals:
Include:
- '**/*.rb'
YAML
create_file(file_path, ['inherit_from: ../src/.rubocop.yml'])
end
it 'gets an absolute AllCops/Exclude' do
excludes = configuration_from_file['AllCops']['Exclude']
expect(excludes).to eq([File.expand_path('src/vendor/**')])
end
it 'gets an Include that is relative to the subdirectory' do
expect(configuration_from_file['Style/StringLiterals']['Include']).to eq(['../src/**/*.rb'])
end
end
context 'when a file inherits and overrides an Exclude' do
let(:file_path) { '.rubocop.yml' }
let(:message) do
'.rubocop.yml: Style/For:Exclude overrides the same parameter in ' \
'.rubocop_2.yml'
end
before do
create_file(file_path, <<~YAML)
inherit_from:
- .rubocop_1.yml
- .rubocop_2.yml
Style/For:
Exclude:
- spec/requests/group_invite_spec.rb
YAML
create_file('.rubocop_1.yml', <<~YAML)
Style/StringLiterals:
Exclude:
- 'spec/models/group_spec.rb'
YAML
create_file('.rubocop_2.yml', <<~YAML)
Style/For:
Exclude:
- 'spec/models/expense_spec.rb'
YAML
end
it 'gets the Exclude overriding the inherited one with a warning' do
expect do
excludes = configuration_from_file['Style/For']['Exclude']
expect(excludes).to eq([File.expand_path('spec/requests/group_invite_spec.rb')])
end.to output(/#{message}/).to_stdout
end
end
context 'when ParserEngine is in base config and gemspec needs to be parsed' do
let(:file_path) { '.rubocop.yml' }
before do
# This reproduces the issue from https://github.com/rubocop/rubocop/issues/14541
# ParserEngine is in base file but no TargetRubyVersion is set anywhere
create_file('.rubocop_base.yml', <<~YAML)
AllCops:
ParserEngine: parser_prism
YAML
create_file('.rubocop.yml', <<~YAML)
inherit_from: .rubocop_base.yml
YAML
# The gemspec will be parsed to detect Ruby version since TargetRubyVersion is not set
create_file('test.gemspec', <<~RUBY)
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = '>= 2.7.0'
end
RUBY
end
it 'can parse gemspec without error even when parser_prism is configured' do
# Without the fix, this would raise:
# ArgumentError: RuboCop supports target Ruby versions 3.3 and above with Prism.
# Specified target Ruby version: 2.7
expect { configuration_from_file }.not_to raise_error
config = configuration_from_file
expect(config.for_all_cops['ParserEngine']).to eq('parser_prism')
expect(config.target_ruby_version).to eq(2.7)
end
end
context 'when TargetRubyVersion and ParserEngine are in separate inherited configs' do
let(:file_path) { '.rubocop.yml' }
before do
# When TargetRubyVersion is explicitly set, there's no issue
create_file('.rubocop_base.yml', <<~YAML)
AllCops:
ParserEngine: parser_prism
YAML
create_file('.rubocop.yml', <<~YAML)
inherit_from: .rubocop_base.yml
AllCops:
TargetRubyVersion: 3.3
YAML
create_file('test.gemspec', <<~RUBY)
Gem::Specification.new do |s|
s.name = 'test'
s.required_ruby_version = '>= 2.7.0'
end
RUBY
end
it 'loads configuration without error when using parser_prism' do
expect { configuration_from_file }.not_to raise_error
config = configuration_from_file
expect(config.for_all_cops['TargetRubyVersion']).to eq(3.3)
expect(config.for_all_cops['ParserEngine']).to eq('parser_prism')
expect(config.target_ruby_version).to eq(3.3)
end
end
context 'when a file inherits from multiple files using a glob' do
let(:file_path) { '.rubocop.yml' }
before do
create_file(file_path, <<~YAML)
inherit_from:
- packages/*/.rubocop_todo.yml
inherit_mode:
merge:
- Exclude
Style/For:
Exclude:
- spec/requests/group_invite_spec.rb
YAML
create_file('packages/package_one/.rubocop_todo.yml', <<~YAML)
Style/For:
Exclude:
- 'spec/models/group_spec.rb'
YAML
create_file('packages/package_two/.rubocop_todo.yml', <<~YAML)
Style/For:
Exclude:
- 'spec/models/expense_spec.rb'
YAML
create_file('packages/package_three/.rubocop_todo.yml', <<~YAML)
Style/For:
Exclude:
- 'spec/models/order_spec.rb'
YAML
end
it 'gets the Exclude merging the inherited one' do
expected = [
File.expand_path('packages/package_two/spec/models/expense_spec.rb'),
File.expand_path('packages/package_one/spec/models/group_spec.rb'),
File.expand_path('packages/package_three/spec/models/order_spec.rb'),
File.expand_path('spec/requests/group_invite_spec.rb')
]
expect(configuration_from_file['Style/For']['Exclude']).to match_array(expected)
end
end
context 'when a file inherits and overrides a hash with nil' do
let(:file_path) { '.rubocop.yml' }
before do
create_file('.rubocop_parent.yml', <<~YAML)
Style/InverseMethods:
InverseMethods:
:any?: :none?
:even?: :odd?
:==: :!=
:=~: :!~
:<: :>=
:>: :<=
YAML
create_file('.rubocop.yml', <<~YAML)
inherit_from: .rubocop_parent.yml
Style/InverseMethods:
InverseMethods:
:<: ~
:>: ~
:foo: :bar
YAML
end
it 'removes hash keys with nil values' do
inverse_methods = configuration_from_file['Style/InverseMethods']['InverseMethods']
expect(inverse_methods).to eq('==': :!=, '=~': :!~, any?: :none?, even?: :odd?, foo: :bar)
end
end
context 'when inherit_mode is set to merge for Exclude' do
let(:file_path) { '.rubocop.yml' }
before do
create_file(file_path, <<~YAML)
inherit_from: .rubocop_parent.yml
inherit_mode:
merge:
- Exclude
AllCops:
Exclude:
- spec/requests/expense_spec.rb
Style/For:
Exclude:
- spec/requests/group_invite_spec.rb
Style/Documentation:
Include:
- extra/*.rb
Exclude:
- junk/*.rb
YAML
create_file('.rubocop_parent.yml', <<~YAML)
Style/For:
Exclude:
- 'spec/models/expense_spec.rb'
- 'spec/models/group_spec.rb'
Style/Documentation:
inherit_mode:
merge:
- Exclude
Exclude:
- funk/*.rb
YAML
end
it 'unions the two lists of Excludes from the parent and child configs ' \
'and does not output a warning' do
expect do
excludes = configuration_from_file['Style/For']['Exclude']
expect(excludes.sort)
.to eq([File.expand_path('spec/requests/group_invite_spec.rb'),
File.expand_path('spec/models/expense_spec.rb'),
File.expand_path('spec/models/group_spec.rb')].sort)
end.not_to output(/overrides the same parameter/).to_stdout
end
it 'merges AllCops:Exclude with the default configuration' do
expect(configuration_from_file['AllCops']['Exclude'].sort)
.to eq(([File.expand_path('spec/requests/expense_spec.rb')] +
default_config['AllCops']['Exclude']).sort)
end
it 'merges Style/Documentation:Exclude with parent and default configuration' do
expect(configuration_from_file['Style/Documentation']['Exclude'].sort)
.to eq(([File.expand_path('funk/*.rb'),
File.expand_path('junk/*.rb')] +
default_config['Style/Documentation']['Exclude']).sort)
end
it 'overrides Style/Documentation:Include' do
expect(configuration_from_file['Style/Documentation']['Include'].sort)
.to eq(['extra/*.rb'].sort)
end
end
context 'when inherit_mode overrides the global inherit_mode setting' do
let(:file_path) { '.rubocop.yml' }
before do
create_file(file_path, <<~YAML)
inherit_from: .rubocop_parent.yml
inherit_mode:
merge:
- Exclude
Style/For:
Exclude:
- spec/requests/group_invite_spec.rb
Style/Dir:
inherit_mode:
override:
- Exclude
Exclude:
- spec/requests/group_invite_spec.rb
YAML
create_file('.rubocop_parent.yml', <<~YAML)
Style/For:
Exclude:
- 'spec/models/expense_spec.rb'
- 'spec/models/group_spec.rb'
Style/Dir:
Exclude:
- 'spec/models/expense_spec.rb'
- 'spec/models/group_spec.rb'
YAML
end
it 'unions the two lists of Excludes from the parent and child configs ' \
'for cops that do not override the inherit_mode' do
expect do
excludes = configuration_from_file['Style/For']['Exclude']
expect(excludes.sort)
.to eq([File.expand_path('spec/requests/group_invite_spec.rb'),
File.expand_path('spec/models/expense_spec.rb'),
File.expand_path('spec/models/group_spec.rb')].sort)
end.not_to output(/overrides the same parameter/).to_stdout
end
it 'overwrites the Exclude from the parent when the cop overrides the global inherit_mode' do
expect do
excludes = configuration_from_file['Style/Dir']['Exclude']
expect(excludes).to eq([File.expand_path('spec/requests/group_invite_spec.rb')])
end.not_to output(/overrides the same parameter/).to_stdout
end
end
context 'when inherit_mode is specified for a nested element even ' \
'without explicitly specifying `inherit_from`/`inherit_gem`' do
let(:file_path) { '.rubocop.yml' }
before do
stub_const('RuboCop::ConfigLoader::RUBOCOP_HOME', 'rubocop')
stub_const('RuboCop::ConfigLoader::DEFAULT_FILE',
File.join('rubocop', 'config', 'default.yml'))
create_file('rubocop/config/default.yml', <<~YAML)
Language:
Examples:
inherit_mode:
merge:
- Regular
- Focused
Regular:
- it
Focused:
- fit
Skipped:
- xit
Pending:
- pending
YAML
create_file(file_path, <<~YAML)
Language:
Examples:
inherit_mode:
merge:
- Skipped
override:
- Focused
Regular:
- scenario
Focused:
- fscenario
Skipped:
- xscenario
Pending:
- later
YAML
end
it 'respects the priority of `inherit_mode`, user-defined first' do
examples_configuration = configuration_from_file['Language']['Examples']
expect(examples_configuration['Regular']).to contain_exactly('it', 'scenario')
expect(examples_configuration['Focused']).to contain_exactly('fscenario')
expect(examples_configuration['Skipped']).to contain_exactly('xit', 'xscenario')
expect(examples_configuration['Pending']).to contain_exactly('later')
end
end
context 'when inherit_mode:merge for a cop lists parameters that are either in parent or in ' \
'default configuration' do
let(:file_path) { '.rubocop.yml' }
before do
create_file('hosted_config.yml', <<~YAML)
AllCops:
NewCops: enable
Naming/VariableNumber:
EnforcedStyle: snake_case
Exclude:
- foo.rb
Include:
- bar.rb
InheritedArraySpecifiedString:
- 'string in array'
InheritedStringSpecifiedArray: 'bare string'
YAML
create_file(file_path, <<~YAML)
inherit_from:
- hosted_config.yml
Naming/VariableNumber:
inherit_mode:
merge:
- AllowedIdentifiers
- Exclude
- Include
- InheritedStringSpecifiedArray
- InheritedArraySpecifiedString
AllowedIdentifiers:
- iso2
Exclude:
- test.rb
Include:
- another_test.rb
InheritedArraySpecifiedString: 'bare string'
InheritedStringSpecifiedArray:
- 'string in array'
YAML
end
it 'merges array parameters with parent or default configuration' do
examples_configuration = configuration_from_file['Naming/VariableNumber']
expect(examples_configuration['Exclude'].map { |abs_path| File.basename(abs_path) })
.to contain_exactly('foo.rb', 'test.rb')
expect(examples_configuration['Include']).to contain_exactly('bar.rb', 'another_test.rb')
expect(examples_configuration['AllowedIdentifiers'])
.to match_array(
%w[TLS1_1 TLS1_2 capture3 iso8601 rfc1123_date rfc2822 rfc3339 rfc822 iso2 x86_64]
)
expect(examples_configuration['InheritedArraySpecifiedString']).to contain_exactly(
'bare string',
'string in array'
)
expect(examples_configuration['InheritedStringSpecifiedArray']).to contain_exactly(
'bare string',
'string in array'
)
end
end
context 'when a department is enabled in the top directory and disabled in a subdirectory' do
let(:file_path) { '.rubocop.yml' }
let(:configuration_from_subdir) do
described_class.configuration_from_file('subdir/.rubocop.yml')
end
before do
stub_const('RuboCop::ConfigLoader::RUBOCOP_HOME', 'rubocop')
stub_const('RuboCop::ConfigLoader::DEFAULT_FILE',
File.join('rubocop', 'config', 'default.yml'))
create_file('rubocop/config/default.yml', <<~YAML)
Layout/SomeCop:
Enabled: pending
YAML
create_file(file_path, <<~YAML)
Layout:
Enabled: true
YAML
create_file('subdir/.rubocop.yml', <<~YAML)
Layout:
Enabled: false
YAML
end
it 'does not disable pending cops of that department in the top directory' do
# The cop is disabled in subdir because its department is disabled there.
subdir_configuration = configuration_from_subdir.for_cop('Layout/SomeCop')
expect(subdir_configuration['Enabled']).to be(false)
# The disabling of the cop in subdir should not leak into the top directory.
examples_configuration = configuration_from_file.for_cop('Layout/SomeCop')
expect(examples_configuration['Enabled']).to eq('pending')
end
end
context 'when a department is disabled', :restore_registry do
let(:file_path) { '.rubocop.yml' }
shared_examples 'resolves enabled/disabled for all ' \
'cops' do |enabled_by_default, disabled_by_default, custom_dept_to_disable|
before { stub_cop_class('RuboCop::Cop::Foo::Bar::Baz') }
it "handles EnabledByDefault: #{enabled_by_default}, " \
"DisabledByDefault: #{disabled_by_default} with disabled #{custom_dept_to_disable}" do
create_file('grandparent_rubocop.yml', <<~YAML)
Layout:
Enabled: false
Layout/EndOfLine:
Enabled: true
Naming/FileName:
Enabled: pending
Metrics/AbcSize:
Enabled: true
Metrics/PerceivedComplexity:
Enabled: true
Lint:
Enabled: false
Foo/Bar/Baz:
Enabled: true
YAML
create_file('parent_rubocop.yml', <<~YAML)
inherit_from: grandparent_rubocop.yml
Metrics:
Enabled: false
Metrics/AbcSize:
Enabled: false
Naming:
Enabled: false
#{custom_dept_to_disable}:
Enabled: false
YAML
create_file(file_path, <<~YAML)
inherit_from: parent_rubocop.yml
AllCops:
EnabledByDefault: #{enabled_by_default}
DisabledByDefault: #{disabled_by_default}
Layout:
Enabled: false
Layout/LineLength:
Enabled: true
Style:
Enabled: false
Metrics/MethodLength:
Enabled: true
Metrics/ClassLength:
Enabled: false
Lint/RaiseException:
Enabled: true
Style/AndOr:
Enabled: true
YAML
def enabled?(cop)
configuration_from_file.for_cop(cop)['Enabled']
end
if custom_dept_to_disable == 'Foo'
message = <<~OUTPUT.chomp
unrecognized cop or department Foo found in parent_rubocop.yml
Foo is not a department. Use `Foo/Bar`.
OUTPUT
expect { enabled?('Foo/Bar/Baz') }.to raise_error(RuboCop::ValidationError, message)
next
end
# Department disabled in grandparent config.
expect(enabled?('Layout/DotPosition')).to be(false)
# Enabled in grandparent config, disabled in user config.
expect(enabled?('Layout/EndOfLine')).to be(false)
# Department disabled in grandparent config, cop enabled in user config.
expect(enabled?('Layout/LineLength')).to be(true)
# Department disabled in parent config, cop enabled in child.
expect(enabled?('Metrics/MethodLength')).to be(true)
# Department disabled in parent config, cop disabled in child.
expect(enabled?('Metrics/ClassLength')).to be(false)
# Enabled in grandparent config, disabled in parent.
expect(enabled?('Metrics/AbcSize')).to be(false)
# Enabled in grandparent config, department disabled in parent.
expect(enabled?('Metrics/PerceivedComplexity')).to be(false)
# Pending in grandparent config, department disabled in parent.
expect(enabled?('Naming/FileName')).to be(false)
# Department disabled in child config.
expect(enabled?('Style/Alias')).to be(false)
# Department disabled in child config, cop enabled in child.
expect(enabled?('Style/AndOr')).to be(true)
# Department disabled in grandparent, cop enabled in child config.
expect(enabled?('Lint/RaiseException')).to be(true)
# Cop enabled in grandparent, nested department disabled in parent.
expect(enabled?('Foo/Bar/Baz')).to be(false)
# Cop with similar prefix to disabled nested department.
expect(enabled?('Foo/BarBaz')).to eq(!disabled_by_default)
# Cop enabled in default config, department disabled in grandparent.
expect(enabled?('Lint/StructNewOverride')).to be(false)
# Cop enabled in default config, but not mentioned in user config.
expect(enabled?('Bundler/DuplicatedGem')).to eq(!disabled_by_default)
end
end
it_behaves_like 'resolves enabled/disabled for all cops', false, false, 'Foo/Bar'
it_behaves_like 'resolves enabled/disabled for all cops', false, true, 'Foo/Bar'
it_behaves_like 'resolves enabled/disabled for all cops', true, false, 'Foo/Bar'
it_behaves_like 'resolves enabled/disabled for all cops', false, false, 'Foo'
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/rake_task_spec.rb | spec/rubocop/rake_task_spec.rb | # frozen_string_literal: true
require 'rubocop/rake_task'
require 'support/file_helper'
RSpec.describe RuboCop::RakeTask do
include FileHelper
before { Rake::Task.clear }
after { Rake::Task.clear }
describe 'defining tasks' do
# rubocop:todo Naming/InclusiveLanguage
it 'creates a rubocop task and a rubocop auto_correct task' do
described_class.new
expect(Rake::Task).to be_task_defined(:rubocop)
expect(Rake::Task).to be_task_defined('rubocop:auto_correct')
end
it 'creates a named task and a named auto_correct task' do
described_class.new(:lint_lib)
expect(Rake::Task).to be_task_defined(:lint_lib)
expect(Rake::Task).to be_task_defined('lint_lib:auto_correct')
end
# rubocop:enable Naming/InclusiveLanguage
it 'creates a rubocop task and a rubocop autocorrect task' do
described_class.new
expect(Rake::Task).to be_task_defined(:rubocop)
expect(Rake::Task).to be_task_defined('rubocop:autocorrect')
end
it 'creates a named task and a named autocorrect task' do
described_class.new(:lint_lib)
expect(Rake::Task).to be_task_defined(:lint_lib)
expect(Rake::Task).to be_task_defined('lint_lib:autocorrect')
end
end
describe 'running tasks' do
include_context 'mock console output'
it 'runs with default options' do
described_class.new
cli = instance_double(RuboCop::CLI, run: 0)
allow(RuboCop::CLI).to receive(:new).and_return(cli)
expect(cli).to receive(:run).with([])
Rake::Task['rubocop'].execute
end
it 'runs with specified options if a block is given' do
described_class.new do |task|
task.patterns = ['lib/**/*.rb']
task.formatters = ['files']
task.fail_on_error = false
task.options = ['--display-cop-names']
task.verbose = false
end
cli = instance_double(RuboCop::CLI, run: 0)
allow(RuboCop::CLI).to receive(:new).and_return(cli)
options = ['--format', 'files', '--display-cop-names', 'lib/**/*.rb']
expect(cli).to receive(:run).with(options)
Rake::Task['rubocop'].execute
end
it 'allows nested arrays inside formatters, options, and requires' do
described_class.new do |task|
task.formatters = [['files']]
task.requires = [['library']]
task.options = [['--display-cop-names']]
end
cli = instance_double(RuboCop::CLI, run: 0)
allow(RuboCop::CLI).to receive(:new).and_return(cli)
options = ['--format', 'files', '--require', 'library', '--display-cop-names']
expect(cli).to receive(:run).with(options)
Rake::Task['rubocop'].execute
end
it 'allows nested arrays inside formatters, options, and plugins' do
described_class.new do |task|
task.formatters = [['files']]
task.plugins = [['extension-plugin']]
task.options = [['--display-cop-names']]
end
cli = instance_double(RuboCop::CLI, run: 0)
allow(RuboCop::CLI).to receive(:new).and_return(cli)
options = ['--format', 'files', '--plugin', 'extension-plugin', '--display-cop-names']
expect(cli).to receive(:run).with(options)
Rake::Task['rubocop'].execute
end
it 'does not error when result is not 0 and fail_on_error is false' do
described_class.new { |task| task.fail_on_error = false }
cli = instance_double(RuboCop::CLI, run: 1)
allow(RuboCop::CLI).to receive(:new).and_return(cli)
expect { Rake::Task['rubocop'].execute }.not_to raise_error
end
it 'exits when result is not 0 and fail_on_error is true' do
described_class.new
cli = instance_double(RuboCop::CLI, run: 1)
allow(RuboCop::CLI).to receive(:new).and_return(cli)
expect { Rake::Task['rubocop'].execute }.to raise_error(SystemExit)
end
it 'uses the default formatter from .rubocop.yml if no formatter ' \
'option is given', :isolated_environment do
create_file('.rubocop.yml', <<~YAML)
AllCops:
DefaultFormatter: offenses
YAML
create_file('test.rb', '$:')
described_class.new { |task| task.options = ['test.rb'] }
expect { Rake::Task['rubocop'].execute }.to raise_error(SystemExit)
expect($stdout.string).to eq(<<~RESULT)
Running RuboCop...
1 Style/FrozenStringLiteralComment [Unsafe Correctable]
1 Style/SpecialGlobalVars [Unsafe Correctable]
--
2 Total in 1 files
RESULT
expect($stderr.string.strip).to eq 'RuboCop failed!'
end
context 'autocorrect' do
it 'runs with --autocorrect' do
described_class.new
cli = instance_double(RuboCop::CLI, run: 0)
allow(RuboCop::CLI).to receive(:new).and_return(cli)
options = ['--autocorrect']
expect(cli).to receive(:run).with(options)
Rake::Task['rubocop:autocorrect'].execute
end
it 'runs with --autocorrect-all' do
described_class.new
cli = instance_double(RuboCop::CLI, run: 0)
allow(RuboCop::CLI).to receive(:new).and_return(cli)
options = ['--autocorrect-all']
expect(cli).to receive(:run).with(options)
Rake::Task['rubocop:autocorrect_all'].execute
end
it 'runs with the options that were passed to its parent task' do
described_class.new do |task|
task.patterns = ['lib/**/*.rb']
task.formatters = ['files']
task.fail_on_error = false
task.options = ['-D']
task.verbose = false
end
cli = instance_double(RuboCop::CLI, run: 0)
allow(RuboCop::CLI).to receive(:new).and_return(cli)
options = ['--autocorrect-all', '--format', 'files', '-D', 'lib/**/*.rb']
expect(cli).to receive(:run).with(options)
Rake::Task['rubocop:autocorrect_all'].execute
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/result_cache_spec.rb | spec/rubocop/result_cache_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::ResultCache, :isolated_environment do
include EncodingHelper
include FileHelper
subject(:cache) { described_class.new(file, team, options, config_store, cache_root) }
let(:registry) { RuboCop::Cop::Registry.global }
let(:team) do
RuboCop::Cop::Team.mobilize(registry, RuboCop::ConfigLoader.default_configuration, options)
end
let(:file) { 'example.rb' }
let(:options) { {} }
let(:config_store) { instance_double(RuboCop::ConfigStore, for_pwd: RuboCop::Config.new) }
let(:cache_root) { "#{Dir.pwd}/.cache" }
let(:rubocop_cache_dir) { "#{Dir.pwd}/.cache/rubocop_cache" }
let(:offenses) do
[RuboCop::Cop::Offense.new(:warning, location, 'unused var', 'Lint/UselessAssignment')]
end
let(:location) do
source_buffer = Parser::Source::Buffer.new(file)
source_buffer.read
Parser::Source::Range.new(source_buffer, 0, 2)
end
def abs(path)
File.expand_path(path)
end
before do
create_file('example.rb', <<~RUBY)
# Hello
x = 1
RUBY
allow(config_store).to receive(:for_file).with('example.rb').and_return(RuboCop::Config.new)
allow(team).to receive(:external_dependency_checksum).and_return('foo')
end
describe 'cached result that was saved with no command line option' do
shared_examples 'valid' do
it 'is valid and can be loaded' do
cache.save(offenses)
cache2 = described_class.new(file, team, options2, config_store, cache_root)
expect(cache2).to be_valid
saved_offenses = cache2.load
expect(saved_offenses).to eq(offenses)
end
end
# Fixes https://github.com/rubocop/rubocop/issues/6274
context 'when offenses are saved' do
context 'an offense with status corrected' do
let(:offense) do
RuboCop::Cop::Offense.new(
:warning, location, 'unused var', 'Lint/UselessAssignment', :corrected
)
end
it 'serializes them with uncorrected status' do
cache.save([offense])
expect(cache.load[0].status).to eq(:uncorrected)
end
end
context 'an offense with status corrected_with_todo' do
let(:offense) do
RuboCop::Cop::Offense.new(
:warning, location, 'unused var', 'Lint/UselessAssignment', :corrected_with_todo
)
end
it 'serializes them with uncorrected status' do
cache.save([offense])
expect(cache.load[0].status).to eq(:uncorrected)
end
end
context 'an offense with status uncorrected' do
let(:offense) do
RuboCop::Cop::Offense.new(
:warning, location, 'unused var', 'Lint/UselessAssignment', :uncorrected
)
end
it 'serializes them with uncorrected status' do
cache.save([offense])
expect(cache.load[0].status).to eq(:uncorrected)
end
end
context 'an offense with status unsupported' do
let(:offense) do
RuboCop::Cop::Offense.new(
:warning, location, 'unused var', 'Lint/UselessAssignment', :unsupported
)
end
it 'serializes them with unsupported status' do
cache.save([offense])
expect(cache.load[0].status).to eq(:unsupported)
end
end
context 'an offense with status new_status' do
let(:offense) do
RuboCop::Cop::Offense.new(
:warning, location, 'unused var', 'Lint/UselessAssignment', :new_status
)
end
it 'serializes them with new_status status' do
cache.save([offense])
expect(cache.load[0].status).to eq(:new_status)
end
end
context 'a global offense' do
let(:no_location) { RuboCop::Cop::Offense::NO_LOCATION }
let(:global_offense) do
RuboCop::Cop::Offense.new(:warning, no_location, 'empty file', 'Lint/EmptyFile',
:unsupported)
end
it 'serializes the range correctly' do
cache.save([global_offense])
expect(cache.load[0].location).to eq(no_location)
end
end
context 'a global Lint/Syntax offense, caused by a parser error' do
before do
create_file('example.rb', ['# encoding: unknown'])
end
let(:no_location) { RuboCop::Cop::Offense::NO_LOCATION }
let(:global_offense) do
RuboCop::Cop::Offense.new(:warning, no_location, 'empty file', 'Lint/Syntax',
:unsupported)
end
it 'serializes the range correctly' do
cache.save([global_offense])
expect(cache.load[0].location).to eq(no_location)
end
end
end
context 'when no option is given' do
let(:options2) { {} }
it_behaves_like 'valid'
context 'when file contents have changed' do
it 'is invalid' do
cache.save(offenses)
create_file('example.rb', ['x = 2'])
cache2 = described_class.new(file, team, options, config_store, cache_root)
expect(cache2).not_to be_valid
end
end
context 'when file permission have changed' do
unless RuboCop::Platform.windows?
it 'is invalid' do
cache.save(offenses)
FileUtils.chmod('+x', file)
cache2 = described_class.new(file, team, options, config_store, cache_root)
expect(cache2).not_to be_valid
end
end
end
context 'when end of line characters have changed' do
it 'is invalid' do
cache.save(offenses)
contents = File.binread(file)
File.open(file, 'wb') do |f|
if contents.include?("\r")
f.write(contents.delete("\r"))
else
f.write(contents.gsub("\n", "\r\n"))
end
end
cache2 = described_class.new(file, team, options, config_store, cache_root)
expect(cache2).not_to be_valid
end
end
context 'when team external_dependency_checksum changes' do
it 'is invalid' do
cache.save(offenses)
allow(team).to(receive(:external_dependency_checksum).and_return('bar'))
cache2 = described_class.new(file, team, options, config_store, cache_root)
expect(cache2).not_to be_valid
end
end
context 'when team external_dependency_checksum is the same' do
it 'is valid' do
cache.save(offenses)
allow(team).to(receive(:external_dependency_checksum).and_return('foo'))
cache2 = described_class.new(file, team, options, config_store, cache_root)
expect(cache2).to be_valid
end
end
context 'when a symlink is present in the cache location' do
include_context 'mock console output'
let(:cache2) { described_class.new(file, team, options, config_store, cache_root) }
let(:attack_target_dir) { Dir.mktmpdir }
before do
# Avoid getting "symlink() function is unimplemented on this
# machine" on Windows.
skip 'Symlinks not implemented on Windows' if RuboCop::Platform.windows?
cache.save(offenses)
result = Dir["#{cache_root}/*/*"]
path = result.first
FileUtils.rm_rf(path)
FileUtils.ln_s(attack_target_dir, path)
end
after do
FileUtils.rm_rf(attack_target_dir)
end
context 'and symlink attack protection is enabled' do
it 'prevents caching and prints a warning' do
cache2.save(offenses)
# The cache file has not been created because there was a symlink in
# its path.
expect(cache2).not_to be_valid
expect($stderr.string).to match(/Warning: .* is a symlink, which is not allowed.\n/)
end
end
context 'and symlink attack protection is disabled' do
before do
allow(config_store).to receive(:for_pwd).and_return(
RuboCop::Config.new(
'AllCops' => {
'AllowSymlinksInCacheRootDirectory' => true
}
)
)
end
it 'permits caching and prints no warning' do
cache2.save(offenses)
expect(cache2).to be_valid
expect($stderr.string).not_to match(/Warning: .* is a symlink, which is not allowed.\n/)
end
end
end
end
context 'when --cache-root is given' do
it 'takes the cache_root from the options' do
cache2 = described_class.new(file, team, { cache_root: 'some/path' }, config_store)
expect(cache2.path).to start_with('some/path/rubocop_cache')
end
end
context 'when --format is given' do
let(:options2) { { format: 'simple' } }
it_behaves_like 'valid'
end
context 'when --only is given' do
it 'is invalid' do
cache.save(offenses)
cache2 = described_class.new(file, team,
{ only: ['Layout/LineLength'] },
config_store, cache_root)
expect(cache2).not_to be_valid
end
end
context 'when --display-cop-names is given' do
it 'is invalid' do
cache.save(offenses)
cache2 = described_class.new(file, team, { display_cop_names: true },
config_store, cache_root)
expect(cache2).not_to be_valid
end
end
context 'when a cache source is read' do
it 'has utf8 encoding' do
cache.save(offenses)
result = cache.load
loaded_encoding = result[0].location.source.encoding
expect(loaded_encoding).to eql(Encoding::UTF_8)
end
end
end
describe '#save' do
context 'when the default internal encoding is UTF-8' do
let(:offenses) do
[
"unused var \xF0",
(+'unused var γ').force_encoding(Encoding::ASCII_8BIT)
].map do |message|
RuboCop::Cop::Offense.new(:warning, location, message, 'Lint/UselessAssignment')
end
end
around do |example|
with_default_internal_encoding(Encoding::UTF_8) { example.run }
end
it 'writes non UTF-8 encodable data to file with no exception' do
expect { cache.save(offenses) }.not_to raise_error
end
end
shared_examples 'invalid cache location' do |error, message|
include_context 'mock console output'
it 'doesn\'t raise an exception' do
allow(FileUtils).to receive(:mkdir_p).with(start_with(cache_root)).and_raise(error)
expect { cache.save([]) }.not_to raise_error
expect($stderr.string).to eq(<<~WARN)
Couldn't create cache directory. Continuing without cache.
#{message}
WARN
end
end
context 'when the @path is not writable' do
let(:cache_root) { '/permission_denied_dir' }
it_behaves_like 'invalid cache location', Errno::EACCES, 'Permission denied'
it_behaves_like 'invalid cache location', Errno::EROFS, 'Read-only file system'
end
end
describe '.cleanup' do
include_context 'mock console output'
before do
cfg = RuboCop::Config.new('AllCops' => { 'MaxFilesInCache' => 1 })
allow(config_store).to receive(:for_pwd).and_return(cfg)
allow(config_store).to receive(:for_file).with('other.rb').and_return(cfg)
create_file('other.rb', ['x = 1'])
end
it 'removes the oldest files in the standard cache_root if needed' do
cache.save(offenses)
underscore_dir = Dir["#{rubocop_cache_dir}/*/*"].first
expect(Dir["#{underscore_dir}/*"].size).to eq(1)
cache.class.cleanup(config_store, :verbose, cache_root)
expect($stdout.string).to eq('')
cache2 = described_class.new('other.rb', team, options, config_store, cache_root)
cache2.save(offenses)
underscore_dir = Dir["#{rubocop_cache_dir}/*/*"].first
expect(Dir["#{underscore_dir}/*"].size).to eq(2)
cache.class.cleanup(config_store, :verbose, cache_root)
expect(File).not_to exist(underscore_dir)
expect($stdout.string).to eq("Removing the 2 oldest files from #{rubocop_cache_dir}\n")
end
it 'removes the oldest files in a custom cache_root if needed' do
custom_cache_root = "#{Dir.pwd}/.custom_cache"
custom_rubocop_cache_dir = "#{Dir.pwd}/.custom_cache/rubocop_cache"
custom_cache = described_class.new('other.rb', team, options, config_store, custom_cache_root)
custom_cache.save(offenses)
custom_cache2 = described_class.new('some.rb', team, options, config_store, custom_cache_root)
custom_cache2.save(offenses)
underscore_dir = Dir["#{custom_rubocop_cache_dir}/*/*"].first
expect(Dir["#{underscore_dir}/*"].size).to eq(2)
custom_cache.class.cleanup(config_store, :verbose, custom_cache_root)
expect(File).not_to exist(underscore_dir)
expect($stdout.string).to eq("Removing the 2 oldest files from #{custom_rubocop_cache_dir}\n")
end
end
describe 'the cache path' do
let(:config_store) { instance_double(RuboCop::ConfigStore) }
let(:puid) { Process.uid.to_s }
before do
all_cops = { 'AllCops' => { 'CacheRootDirectory' => cache_root_directory } }
config = RuboCop::Config.new(all_cops)
allow(config_store).to receive(:for_pwd).and_return(config)
end
context 'when CacheRootDirectory not set' do
let(:cache_root_directory) { nil }
context 'and XDG_CACHE_HOME is not set' do
before { ENV['XDG_CACHE_HOME'] = nil }
it 'contains $HOME/.cache' do
cacheroot = described_class.cache_root(config_store)
expect(cacheroot).to eq(File.join(Dir.home, '.cache', 'rubocop_cache'))
end
it 'contains the root in path only once' do
cache = described_class.new(file, team, options, config_store)
expect(cache.path).to start_with(File.join(Dir.home, '.cache', 'rubocop_cache'))
count = cache.path.scan('rubocop_cache').count
expect(count).to eq(1)
end
end
context 'and XDG_CACHE_HOME is set' do
around do |example|
ENV['XDG_CACHE_HOME'] = '/etc/rccache'
begin
example.run
ensure
ENV.delete('XDG_CACHE_HOME')
end
end
it 'contains the given path and UID' do
cacheroot = described_class.cache_root(config_store)
expect(cacheroot).to eq(File.join(ENV.fetch('XDG_CACHE_HOME'), puid, 'rubocop_cache'))
end
it 'contains the root in path only once' do
cache = described_class.new(file, team, options, config_store)
expect(cache.path).to start_with(
File.join(ENV.fetch('XDG_CACHE_HOME'), puid, 'rubocop_cache')
)
count = cache.path.scan('rubocop_cache').count
expect(count).to eq(1)
end
end
end
context 'when CacheRootDirectory is set' do
let(:cache_root_directory) { '/opt' }
it 'contains the given root' do
cacheroot = described_class.cache_root(config_store)
expect(cacheroot).to eq(File.join('/opt', 'rubocop_cache'))
end
context 'and RUBOCOP_CACHE_ROOT is set' do
around do |example|
ENV['RUBOCOP_CACHE_ROOT'] = '/tmp/cache-from-env'
begin
example.run
ensure
ENV.delete('RUBOCOP_CACHE_ROOT')
end
end
it 'contains the root from RUBOCOP_CACHE_ROOT' do
cacheroot = described_class.cache_root(config_store)
expect(cacheroot).to eq(File.join('/tmp/cache-from-env', 'rubocop_cache'))
end
it 'contains the root in path only once' do
cache = described_class.new(file, team, options, config_store)
expect(cache.path).to start_with(File.join('/tmp/cache-from-env', 'rubocop_cache'))
count = cache.path.scan('rubocop_cache').count
expect(count).to eq(1)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/runner_spec.rb | spec/rubocop/runner_spec.rb | # frozen_string_literal: true
module RuboCop
class Runner
attr_writer :errors # Needed only for testing.
end
end
RSpec.describe RuboCop::Runner, :isolated_environment do
include FileHelper
let(:formatter_output_path) { 'formatter_output.txt' }
let(:formatter_output) { File.read(formatter_output_path) }
describe '#run when interrupted' do
include_context 'cli spec behavior'
let(:runner) { described_class.new({}, RuboCop::ConfigStore.new) }
before { create_empty_file('example.rb') }
def interrupt(pid)
Process.kill 'INT', pid
end
def wait_for_input(io)
line = nil
until line
line = io.gets
sleep 0.1
end
line
end
around do |example|
old_handler = Signal.trap('INT', 'DEFAULT')
example.run
Signal.trap('INT', old_handler)
end
context 'with SIGINT' do
it 'returns false' do
skip '`Process` does not respond to `fork` method.' unless Process.respond_to?(:fork)
# Make sure the runner works slowly and thus is interruptible
allow(runner).to receive(:process_file) do
sleep 99
end
rd, wr = IO.pipe
pid = Process.fork do
rd.close
wr.puts 'READY'
wr.puts runner.run(['example.rb'])
wr.close
end
wr.close
# Make sure the runner has started by waiting for a specific message
line = wait_for_input(rd)
expect(line.chomp).to eq('READY')
# Interrupt the runner
interrupt(pid)
# Make sure the runner returns false
line = wait_for_input(rd)
expect(line.chomp).to eq('false')
end
end
end
describe '#run' do
subject(:runner) { described_class.new(options, RuboCop::ConfigStore.new) }
before { create_file('example.rb', source) }
let(:options) { { formatters: [['progress', formatter_output_path]] } }
context 'if there are no offenses in inspected files' do
let(:source) { <<~RUBY }
# frozen_string_literal: true
def valid_code; end
RUBY
it 'returns true' do
expect(runner.run([])).to be true
end
end
context 'if there is an offense in an inspected file' do
let(:source) { <<~RUBY }
# frozen_string_literal: true
def INVALID_CODE; end
RUBY
it 'returns false' do
expect(runner.run([])).to be false
end
it 'sends the offense to a formatter' do
runner.run([])
expect(formatter_output).to eq <<~RESULT
Inspecting 1 file
C
Offenses:
example.rb:3:5: C: Naming/MethodName: Use snake_case for method names.
def INVALID_CODE; end
^^^^^^^^^^^^
1 file inspected, 1 offense detected
RESULT
end
end
context 'custom ruby extractors' do
around do |example|
described_class.ruby_extractors.unshift(custom_ruby_extractor)
# Ignore platform differences.
create_file('.rubocop.yml', <<~YAML)
Layout/EndOfLine:
Enabled: false
YAML
example.call
ensure
described_class.ruby_extractors.shift
end
context 'when the extractor matches' do
# rubocop:disable Layout/LineLength
let(:custom_ruby_extractor) do
lambda do |_processed_source|
[
{
offset: 1,
processed_source: RuboCop::ProcessedSource.new(<<~RUBY, 3.3, 'dummy.rb', parser_engine: parser_engine)
# frozen_string_literal: true
def valid_code; end
RUBY
},
{
offset: 2,
processed_source: RuboCop::ProcessedSource.new(source, 3.3, 'dummy.rb', parser_engine: parser_engine)
}
]
end
end
# rubocop:enable Layout/LineLength
let(:source) do
<<~RUBY
# frozen_string_literal: true
def INVALID_CODE; end
RUBY
end
it 'sends the offense to a formatter' do
runner.run([])
expect(formatter_output).to eq <<~RESULT
Inspecting 1 file
C
Offenses:
example.rb:3:7: C: Naming/MethodName: Use snake_case for method names.
def INVALID_CODE; end
^^^^^^^^^^^^
1 file inspected, 1 offense detected
RESULT
end
end
context 'when the extractor does not match' do
let(:custom_ruby_extractor) do
lambda do |_processed_source|
end
end
let(:source) { <<~RUBY }
# frozen_string_literal: true
def INVALID_CODE; end
RUBY
it 'sends the offense to a formatter' do
runner.run([])
expect(formatter_output).to eq <<~RESULT
Inspecting 1 file
C
Offenses:
example.rb:3:5: C: Naming/MethodName: Use snake_case for method names.
def INVALID_CODE; end
^^^^^^^^^^^^
1 file inspected, 1 offense detected
RESULT
end
end
context 'when the extractor crashes' do
let(:source) { <<~RUBY }
# frozen_string_literal: true
def foo; end
RUBY
shared_examples 'error handling' do
it 'raises an error with the crashing extractor/file' do
expect do
runner.run([])
end.to raise_error(RuboCop::Error, /runner_spec\.rb failed to process .*example\.rb/)
end
end
context 'and it is a Proc' do
let(:custom_ruby_extractor) do
lambda do |_processed_source|
raise 'Oh no!'
end
end
it_behaves_like 'error handling'
end
context 'and it responds to `call`' do
let(:custom_ruby_extractor) do
Class.new do
def self.call(_processed_source)
raise 'Oh no!'
end
end
end
it_behaves_like 'error handling'
end
end
end
context 'if a cop crashes' do
before do
# The cache responds that it's not valid, which means that new results
# should normally be collected and saved...
cache = instance_double(RuboCop::ResultCache, 'valid?' => false)
# ... but there's a crash in one cop.
runner.errors = ['An error occurred in ...']
allow(RuboCop::ResultCache).to receive(:new) { cache }
end
let(:source) { '' }
it 'does not call ResultCache#save' do
# The double doesn't define #save, so we'd get an error if it were
# called.
expect(runner.run([])).to be true
end
end
context 'if -s/--stdin is used with an offense' do
before do
# Make Style/EndOfLine give same output regardless of platform.
create_file('.rubocop.yml', <<~YAML)
Layout/EndOfLine:
EnforcedStyle: lf
YAML
end
let(:options) do
{
formatters: [['progress', formatter_output_path]],
stdin: <<~RUBY
# frozen_string_literal: true
def INVALID_CODE; end
RUBY
}
end
let(:source) { '' }
it 'returns false' do
expect(runner.run([])).to be false
end
it 'sends the offense to a formatter' do
runner.run([])
expect(formatter_output).to eq <<~RESULT
Inspecting 1 file
C
Offenses:
example.rb:3:5: C: Naming/MethodName: Use snake_case for method names.
def INVALID_CODE; end
^^^^^^^^^^^^
1 file inspected, 1 offense detected
RESULT
end
end
end
describe '#run with cops autocorrecting each-other' do
include_context 'mock console output'
let!(:source_file_path) { create_file('example.rb', source) }
let(:options) { { autocorrect: true } }
context 'with two conflicting cops' do
subject(:runner) do
runner_class = Class.new(RuboCop::Runner) do
def mobilized_cop_classes(_config)
RuboCop::Cop::Registry.new(
[
RuboCop::Cop::Test::ClassMustBeAModuleCop,
RuboCop::Cop::Test::ModuleMustBeAClassCop
]
)
end
end
runner_class.new(options, RuboCop::ConfigStore.new)
end
context 'if there is an offense in an inspected file' do
let(:source) { <<~RUBY }
# frozen_string_literal: true
class Klass
end
RUBY
it 'records the infinite loop error' do
runner.run([])
expect(runner.errors.size).to be(1)
expect(runner.errors[0].message).to eq(
"Infinite loop detected in #{source_file_path} and caused by " \
'Test/ClassMustBeAModuleCop -> Test/ModuleMustBeAClassCop'
)
end
context 'when `raise_cop_error` is set' do
let(:options) { { autocorrect: true, raise_cop_error: true } }
it 'raises the infinite loop error' do
expect do
runner.run([])
end.to raise_error(
described_class::InfiniteCorrectionLoop,
"Infinite loop detected in #{source_file_path} and caused by " \
'Test/ClassMustBeAModuleCop -> Test/ModuleMustBeAClassCop'
)
end
end
end
context 'if there are multiple offenses in an inspected file' do
let(:source) { <<~RUBY }
# frozen_string_literal: true
class Klass
end
class AnotherKlass
end
RUBY
it 'records the infinite loop error' do
runner.run([])
expect(runner.errors.size).to be(1)
expect(runner.errors[0].message).to eq(
"Infinite loop detected in #{source_file_path} and caused by " \
'Test/ClassMustBeAModuleCop -> Test/ModuleMustBeAClassCop'
)
end
end
end
context 'with two pairs of conflicting cops' do
subject(:runner) do
runner_class = Class.new(RuboCop::Runner) do
def mobilized_cop_classes(_config)
RuboCop::Cop::Registry.new(
[
RuboCop::Cop::Test::ClassMustBeAModuleCop,
RuboCop::Cop::Test::ModuleMustBeAClassCop,
RuboCop::Cop::Test::AtoB,
RuboCop::Cop::Test::BtoA
]
)
end
end
runner_class.new(options, RuboCop::ConfigStore.new)
end
context 'if there is an offense in an inspected file' do
let(:source) { <<~RUBY }
# frozen_string_literal: true
class A_A
end
RUBY
it 'records the infinite loop error' do
runner.run([])
expect(runner.errors.size).to be(1)
expect(runner.errors[0].message).to eq(
"Infinite loop detected in #{source_file_path} and caused by " \
'Test/ClassMustBeAModuleCop, Test/AtoB -> Test/ModuleMustBeAClassCop, Test/BtoA'
)
end
end
context 'with three cop cycle' do
subject(:runner) do
runner_class = Class.new(RuboCop::Runner) do
def mobilized_cop_classes(_config)
RuboCop::Cop::Registry.new(
[
RuboCop::Cop::Test::AtoB,
RuboCop::Cop::Test::BtoC,
RuboCop::Cop::Test::CtoA
]
)
end
end
runner_class.new(options, RuboCop::ConfigStore.new)
end
context 'if there is an offense in an inspected file' do
let(:source) { <<~RUBY }
# frozen_string_literal: true
class A
end
RUBY
it 'records the infinite correction error' do
runner.run([])
expect(runner.errors.size).to be(1)
expect(runner.errors[0].message).to eq(
"Infinite loop detected in #{source_file_path} and caused by " \
'Test/AtoB -> Test/BtoC -> Test/CtoA'
)
end
end
end
context 'with display options' do
subject(:runner) { described_class.new(options, RuboCop::ConfigStore.new) }
before { create_file('example.rb', source) }
context '--display-only-safe-correctable' do
let(:options) do
{
formatters: [['progress', formatter_output_path]],
display_only_safe_correctable: true
}
end
let(:source) { <<~RUBY }
def foo()
end
RUBY
it 'returns false' do
expect(runner.run([])).to be false
end
it 'omits unsafe correctable `Style/FrozenStringLiteral`' do
runner.run([])
expect(formatter_output).to eq <<~RESULT
Inspecting 1 file
C
Offenses:
example.rb:2:1: C: [Correctable] Layout/LeadingEmptyLines: Unnecessary blank line at the beginning of the source.
def foo()
^^^
example.rb:2:1: C: [Correctable] Style/EmptyMethod: Put empty method definitions on a single line.
def foo() ...
^^^^^^^^^
example.rb:2:8: C: [Correctable] Style/DefWithParentheses: Omit the parentheses in defs when the method doesn't accept any arguments.
def foo()
^^
1 file inspected, 3 offenses detected, 3 offenses autocorrectable
RESULT
end
end
context '--display-only-correctable' do
let(:options) do
{
formatters: [['progress', formatter_output_path]],
display_only_correctable: true
}
end
let(:source) { <<~RUBY }
def foo()
end
'very-long-string-to-earn-un-autocorrectable-offense very-long-string-to-earn-un-autocorrectable-offense very-long-string-to-earn-un-autocorrectable-offense'
RUBY
it 'returns false' do
expect(runner.run([])).to be false
end
it 'omits uncorrectable `Layout/LineLength`' do
runner.run([])
expect(formatter_output).to eq <<~RESULT
Inspecting 1 file
C
Offenses:
example.rb:1:1: C: [Correctable] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
example.rb:2:1: C: [Correctable] Layout/LeadingEmptyLines: Unnecessary blank line at the beginning of the source.
def foo()
^^^
example.rb:2:1: C: [Correctable] Style/EmptyMethod: Put empty method definitions on a single line.
def foo() ...
^^^^^^^^^
example.rb:2:8: C: [Correctable] Style/DefWithParentheses: Omit the parentheses in defs when the method doesn't accept any arguments.
def foo()
^^
1 file inspected, 4 offenses detected, 4 offenses autocorrectable
RESULT
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/config_spec.rb | spec/rubocop/config_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Config do
include FileHelper
subject(:configuration) { described_class.new(hash, loaded_path) }
let(:hash) { {} }
let(:loaded_path) { 'example/.rubocop.yml' }
describe '.new' do
context 'without arguments' do
subject(:configuration) { described_class.new }
it { expect(configuration['Lint/BooleanSymbol']['SafeAutoCorrect']).to be(false) }
end
end
describe '#validate', :isolated_environment do
subject(:configuration) do
# ConfigLoader.load_file will validate config
RuboCop::ConfigLoader.load_file(configuration_path)
end
let(:configuration_path) { '.rubocop.yml' }
context 'when the configuration includes any unrecognized cop name' do
include_context 'mock console output'
before do
create_file(configuration_path, <<~YAML)
LyneLenth:
Enabled: true
Max: 100
YAML
end
it 'raises a validation error' do
expect { configuration }.to raise_error(
RuboCop::ValidationError,
'unrecognized cop or department LyneLenth found in .rubocop.yml'
)
end
end
context 'when the configuration includes any unrecognized cop name and given `--ignore-unrecognized-cops` option' do
context 'there is unrecognized cop' do
include_context 'mock console output'
before do
create_file(configuration_path, <<~YAML)
LyneLenth:
Enabled: true
Max: 100
YAML
RuboCop::ConfigLoader.ignore_unrecognized_cops = true
end
after do
RuboCop::ConfigLoader.ignore_unrecognized_cops = nil
end
it 'prints a warning about the cop' do
configuration
expect($stderr.string)
.to eq("The following cops or departments are not recognized and will be ignored:\n" \
"unrecognized cop or department LyneLenth found in .rubocop.yml\n")
end
end
context 'there are no unrecognized cops' do
include_context 'mock console output'
before do
create_file(configuration_path, <<~YAML)
Layout/LineLength:
Enabled: true
YAML
RuboCop::ConfigLoader.ignore_unrecognized_cops = true
end
after do
RuboCop::ConfigLoader.ignore_unrecognized_cops = nil
end
it 'does not print any warnings' do
configuration
expect($stderr.string).to eq('')
end
end
end
context 'when the configuration includes an empty section' do
before { create_file(configuration_path, ['Layout/LineLength:']) }
it 'raises validation error' do
expect { configuration.validate }
.to raise_error(RuboCop::ValidationError,
%r{^empty section "Layout/LineLength"})
end
end
context 'when the configuration has the wrong type' do
before { create_file(configuration_path, ['Layout/LineLength: Enabled']) }
it 'raises validation error' do
expect { configuration.validate }.to(
raise_error(
RuboCop::ValidationError,
%r{^The configuration for "Layout/LineLength" in .* is not a Hash.\n\nFound: "Enabled"}
)
)
end
end
context 'when the empty section is AllCops' do
before { create_file(configuration_path, ['AllCops:']) }
it 'raises validation error' do
expect { configuration.validate }
.to raise_error(RuboCop::ValidationError, /^empty section "AllCops"/)
end
end
context 'when the configuration is in the base RuboCop config folder' do
before do
create_file(configuration_path, <<~YAML)
InvalidProperty:
Enabled: true
YAML
stub_const('RuboCop::ConfigLoader::RUBOCOP_HOME', rubocop_home_path)
end
let(:rubocop_home_path) { File.realpath('.') }
let(:configuration_path) { 'config/.rubocop.yml' }
it 'is not validated' do
expect { configuration.validate }.not_to raise_error
end
end
context 'when the configuration includes any unrecognized parameter' do
include_context 'mock console output'
before do
create_file(configuration_path, <<~YAML)
Layout/LineLength:
Enabled: true
Min: 10
YAML
end
it 'prints a warning message' do
configuration # ConfigLoader.load_file will validate config
expect($stderr.string).to match(%r{Layout/LineLength does not support Min parameter.})
end
end
context 'when the configuration includes any common parameter' do
# Common parameters are parameters that are not in the default
# configuration, but are nonetheless allowed for any cop.
before do
create_file(configuration_path, <<~YAML)
Metrics/ModuleLength:
Exclude:
- lib/file.rb
Include:
- lib/file.xyz
Severity: warning
inherit_mode:
merge:
- Exclude
StyleGuide: https://example.com/some-style.html
YAML
end
it 'does not raise validation error' do
expect { configuration.validate }.not_to raise_error
end
end
context 'when the configuration includes a valid EnforcedStyle' do
before do
create_file(configuration_path, <<~YAML)
Style/AndOr:
EnforcedStyle: conditionals
YAML
end
it 'does not raise validation error' do
expect { configuration.validate }.not_to raise_error
end
end
context 'when the configuration includes an invalid EnforcedStyle' do
before do
create_file(configuration_path, <<~YAML)
Style/AndOr:
EnforcedStyle: itisinvalid
YAML
end
it 'raises validation error' do
expect { configuration.validate }.to raise_error(RuboCop::ValidationError, /itisinvalid/)
end
end
context 'when the configuration includes a valid enforced style' do
before do
create_file(configuration_path, <<~YAML)
Layout/SpaceAroundBlockParameters:
EnforcedStyleInsidePipes: space
YAML
end
it 'does not raise validation error' do
expect { configuration.validate }.not_to raise_error
end
end
context 'when the configuration includes an invalid enforced style' do
before do
create_file(configuration_path, <<~YAML)
Layout/SpaceAroundBlockParameters:
EnforcedStyleInsidePipes: itisinvalid
YAML
end
it 'raises validation error' do
expect { configuration.validate }.to raise_error(RuboCop::ValidationError, /itisinvalid/)
end
end
context 'when the configuration includes multiple valid enforced styles' do
before do
create_file(configuration_path, <<~YAML)
Layout/HashAlignment:
EnforcedHashRocketStyle:
- key
- table
YAML
end
it 'does not raise validation error' do
expect { configuration.validate }.not_to raise_error
end
end
context 'when the configuration includes multiple valid enforced styles ' \
'and one invalid style' do
before do
create_file(configuration_path, <<~YAML)
Layout/HashAlignment:
EnforcedHashRocketStyle:
- key
- trailing_comma
YAML
end
it 'raises validation error' do
expect { configuration.validate }.to raise_error(RuboCop::ValidationError, /trailing_comma/)
end
end
context 'when the configuration includes multiple but config does not allow' do
before do
create_file(configuration_path, <<~YAML)
Layout/SpaceAroundBlockParameters:
EnforcedStyleInsidePipes:
- space
YAML
end
it 'raises validation error' do
expect { configuration.validate }.to raise_error(RuboCop::ValidationError, /space/)
end
end
context 'when the configuration includes multiple invalid enforced styles' do
before do
create_file(configuration_path, <<~YAML)
Layout/HashAlignment:
EnforcedHashRocketStyle:
- table
- itisinvalid
YAML
end
it 'raises validation error' do
expect { configuration.validate }.to raise_error(RuboCop::ValidationError, /itisinvalid/)
end
end
context 'when the configuration includes an obsolete cop' do
before do
create_file(configuration_path, <<~YAML)
Style/MethodCallParentheses:
Enabled: true
YAML
end
it 'raises validation error' do
expect { configuration.validate }
.to raise_error(RuboCop::ValidationError,
%r{Style/MethodCallWithoutArgsParentheses})
end
end
context 'when the configuration includes an obsolete parameter' do
before do
create_file(configuration_path, <<~YAML)
Rails/UniqBeforePluck:
EnforcedMode: conservative
YAML
end
it 'raises validation error' do
expect { configuration.validate }.to raise_error(RuboCop::ValidationError, /EnforcedStyle/)
end
end
context 'when the configuration includes an obsolete EnforcedStyle parameter' do
before do
create_file(configuration_path, <<~YAML)
Layout/IndentationConsistency:
EnforcedStyle: rails
YAML
end
it 'raises validation error' do
expect { configuration.validate }
.to raise_error(RuboCop::ValidationError,
/EnforcedStyle: rails` has been renamed/)
end
end
shared_examples 'obsolete MaxLineLength parameter' do |cop_name|
context "when the configuration includes the obsolete #{cop_name}: " \
'MaxLineLength parameter' do
before do
create_file(configuration_path, <<~YAML)
#{cop_name}:
MaxLineLength: 100
YAML
end
it 'raises validation error' do
expect { configuration.validate }
.to raise_error(RuboCop::ValidationError,
/`#{cop_name}: MaxLineLength` has been removed./)
end
end
end
it_behaves_like 'obsolete MaxLineLength parameter', 'Style/WhileUntilModifier'
it_behaves_like 'obsolete MaxLineLength parameter', 'Style/IfUnlessModifier'
context 'when the configuration includes obsolete parameters and cops' do
before do
create_file(configuration_path, <<~YAML)
Rails/UniqBeforePluck:
EnforcedMode: conservative
Style/MethodCallParentheses:
Enabled: false
Layout/BlockAlignment:
AlignWith: either
Layout/SpaceBeforeModifierKeyword:
Enabled: false
YAML
end
it 'raises validation error' do
message_matcher = lambda do |message|
message.include?('EnforcedStyle') &&
message.include?('MethodCallWithoutArgsParentheses') &&
message.include?('EnforcedStyleAlignWith') &&
message.include?('Layout/SpaceAroundKeyword')
end
expect { configuration.validate }.to raise_error(RuboCop::ValidationError, message_matcher)
end
end
context 'when the configuration includes obsolete cop names that raise warnings', :mock_obsoletion do
before do
create_file(configuration_path, <<~YAML)
Layout/AlignArguments:
Enabled: false
YAML
create_file(obsoletion_configuration_path, <<~YAML)
renamed:
Layout/AlignArguments:
new_name: Layout/ArgumentAlignment
severity: warning
YAML
end
it 'does not raise validation error' do
expect { configuration.validate }.not_to raise_error
end
end
context 'when all cops are both Enabled and Disabled by default' do
before do
create_file(configuration_path, <<~YAML)
AllCops:
EnabledByDefault: true
DisabledByDefault: true
YAML
end
it 'raises validation error' do
expect { configuration.validate }
.to raise_error(
RuboCop::ValidationError,
/Cops cannot be both enabled by default and disabled by default/
)
end
end
context 'when the configuration includes Lint/Syntax cop' do
before do
# Force reloading default configuration
RuboCop::ConfigLoader.default_configuration = nil
end
context 'when the configuration matches the default' do
before do
create_file(configuration_path, <<~YAML)
Lint/Syntax:
Enabled: true
YAML
end
it 'does not raise validation error' do
expect { configuration.validate }.not_to raise_error
end
end
context 'when the configuration does not match the default' do
before do
create_file(configuration_path, <<~YAML)
Lint/Syntax:
Enabled: false
YAML
end
it 'raises validation error' do
expect { configuration.validate }
.to raise_error(
RuboCop::ValidationError,
%r{configuration for Lint/Syntax cop found}
)
end
end
end
describe 'conflicting Safe settings' do
context 'when the configuration includes an unsafe cop that is ' \
'explicitly declared to have a safe autocorrection' do
before do
create_file(configuration_path, <<~YAML)
Style/PreferredHashMethods:
Safe: false
SafeAutoCorrect: true
YAML
end
it 'raises validation error' do
expect { configuration.validate }
.to raise_error(
RuboCop::ValidationError,
/Unsafe cops cannot have a safe autocorrection/
)
end
end
context 'when the configuration includes an unsafe cop without ' \
'a declaration of its autocorrection' do
before do
create_file(configuration_path, <<~YAML)
Style/PreferredHashMethods:
Safe: false
YAML
end
it 'does not raise validation error' do
expect { configuration.validate }.not_to raise_error
end
end
end
end
describe '#make_excludes_absolute' do
context 'when config is in root directory' do
let(:hash) { { 'AllCops' => { 'Exclude' => ['config/environment', 'spec'] } } }
before do
allow(configuration)
.to receive(:base_dir_for_path_parameters)
.and_return('/home/foo/project')
configuration.make_excludes_absolute
end
it 'generates valid absolute directory' do
excludes = configuration['AllCops']['Exclude'].map { |e| e.sub(/^[A-Z]:/i, '') }
expect(excludes).to eq ['/home/foo/project/config/environment', '/home/foo/project/spec']
end
end
context 'when config is in subdirectory' do
let(:hash) do
{
'AllCops' => {
'Exclude' => [
'../../config/environment',
'../../spec'
]
}
}
end
before do
allow(configuration)
.to receive(:base_dir_for_path_parameters)
.and_return('/home/foo/project/config/tools')
configuration.make_excludes_absolute
end
it 'generates valid absolute directory' do
excludes = configuration['AllCops']['Exclude'].map { |e| e.sub(/^[A-Z]:/i, '') }
expect(excludes).to eq ['/home/foo/project/config/environment', '/home/foo/project/spec']
end
end
end
describe '#file_to_include?' do
let(:hash) { { 'AllCops' => { 'Include' => ['**/Gemfile', 'config/unicorn.rb.example'] } } }
let(:loaded_path) { '/home/foo/project/.rubocop.yml' }
context 'when the passed path matches any of patterns to include' do
it 'returns true' do
file_path = '/home/foo/project/Gemfile'
expect(configuration).to be_file_to_include(file_path)
end
end
context 'when the passed path does not match any of patterns to include' do
it 'returns false' do
file_path = '/home/foo/project/Gemfile.lock'
expect(configuration).not_to be_file_to_include(file_path)
end
end
end
describe '#file_to_exclude?' do
include_context 'mock console output'
let(:hash) { { 'AllCops' => { 'Exclude' => ["#{Dir.pwd}/log/**/*", '**/bar.rb'] } } }
let(:loaded_path) { '/home/foo/project/.rubocop.yml' }
context 'when the passed path matches any of patterns to exclude' do
it 'returns true' do
file_path = "#{Dir.pwd}/log/foo.rb"
expect(configuration).to be_file_to_exclude(file_path)
expect(configuration).to be_file_to_exclude('log/foo.rb')
expect(configuration).to be_file_to_exclude('bar.rb')
end
end
context 'when the passed path does not match any of patterns to exclude' do
it 'returns false' do
file_path = "#{Dir.pwd}/log_file.rb"
expect(configuration).not_to be_file_to_exclude(file_path)
expect(configuration).not_to be_file_to_exclude('app/controller.rb')
expect(configuration).not_to be_file_to_exclude('baz.rb')
end
end
end
describe '#allowed_camel_case_file?' do
subject { configuration.allowed_camel_case_file?(file_path) }
let(:hash) { { 'AllCops' => { 'Include' => ['**/Gemfile'] } } }
context 'when the passed path matches allowed camel case patterns to include' do
let(:file_path) { '/home/foo/project/Gemfile' }
it { is_expected.to be true }
end
context 'when the passed path does not match allowed camel case patterns to include' do
let(:file_path) { '/home/foo/project/testCase' }
it { is_expected.to be false }
end
context 'when the passed path is a gemspec' do
let(:file_path) { '/home/foo/project/my-project.gemspec' }
it { is_expected.to be true }
end
end
describe '#patterns_to_include' do
subject(:patterns_to_include) do
configuration = described_class.new(hash, loaded_path)
configuration.patterns_to_include
end
let(:loaded_path) { 'example/.rubocop.yml' }
context 'when config file has AllCops => Include key' do
let(:hash) do
{
'AllCops' => {
'Include' => ['**/Gemfile', 'config/unicorn.rb.example']
}
}
end
it 'returns the Include value' do
expect(patterns_to_include).to eq(['**/Gemfile', 'config/unicorn.rb.example'])
end
end
end
describe '#possibly_include_hidden?' do
subject(:configuration) { described_class.new(hash, loaded_path) }
let(:loaded_path) { 'example/.rubocop.yml' }
it 'returns true when Include config only includes regular paths' do
configuration['AllCops'] = { 'Include' => ['**/Gemfile', 'config/unicorn.rb.example'] }
expect(configuration).not_to be_possibly_include_hidden
end
it 'returns true when Include config includes a regex' do
configuration['AllCops'] = { 'Include' => [/foo/] }
expect(configuration).to be_possibly_include_hidden
end
it 'returns true when Include config includes a toplevel dotfile' do
configuration['AllCops'] = { 'Include' => ['.foo'] }
expect(configuration).to be_possibly_include_hidden
end
it 'returns true when Include config includes a dotfile in a path' do
configuration['AllCops'] = { 'Include' => ['foo/.bar'] }
expect(configuration).to be_possibly_include_hidden
end
end
describe '#patterns_to_exclude' do
subject(:patterns_to_exclude) do
configuration = described_class.new(hash, loaded_path)
configuration.patterns_to_exclude
end
let(:loaded_path) { 'example/.rubocop.yml' }
context 'when config file has AllCops => Exclude key' do
let(:hash) { { 'AllCops' => { 'Exclude' => ['log/*'] } } }
it 'returns the Exclude value' do
expect(patterns_to_exclude).to eq(['log/*'])
end
end
end
describe '#check' do
subject(:configuration) { described_class.new(hash, loaded_path) }
let(:loaded_path) { 'example/.rubocop.yml' }
context 'when a deprecated configuration is detected' do
include_context 'mock console output'
let(:hash) { { 'AllCops' => { 'Includes' => [] } } }
it 'prints a warning message for the loaded path' do
configuration.check
expect($stderr.string).to include("#{loaded_path} - AllCops/Includes was renamed")
end
end
end
describe '#deprecation_check' do
context 'when there is no AllCops configuration' do
let(:hash) { {} }
it 'does not yield' do
expect { |b| configuration.deprecation_check(&b) }.not_to yield_control
end
end
context 'when there is AllCops configuration' do
context 'if there are no Excludes or Includes keys' do
let(:hash) { { 'AllCops' => { 'Exclude' => [], 'Include' => [] } } }
it 'does not yield' do
expect { |b| configuration.deprecation_check(&b) }.not_to yield_control
end
end
context 'if there are is an Includes key' do
let(:hash) { { 'AllCops' => { 'Includes' => [] } } }
it 'yields' do
expect { |b| configuration.deprecation_check(&b) }.to yield_with_args(String)
end
end
context 'if there are is an Excludes key' do
let(:hash) { { 'AllCops' => { 'Excludes' => [] } } }
it 'yields' do
expect { |b| configuration.deprecation_check(&b) }.to yield_with_args(String)
end
end
end
end
describe '#for_cop', :isolated_environment, :mock_obsoletion do
before do
create_file(obsoletion_configuration_path, <<~YAML)
renamed:
Lint/OldCop:
new_name: Lint/NewCop
Lint/MovedCop:
new_name: Lint/AnotherCop
YAML
end
let(:hash) do
{
'Style' => { 'Enabled' => false, 'Foo' => 42, 'Bar' => 666 },
'Style/Alias' => { 'Bar' => 44 },
'Lint/MovedCop' => { 'Bar' => 45 },
'Lint/OldCop' => { 'Bar' => 46, 'Enabled' => false },
'Lint/NewCop' => { 'Bar' => 47, 'Baz' => 1000 }
}
end
it 'returns the configuration for a cop' do
expect(configuration.for_cop('Style/Alias')).to eq({ 'Enabled' => false, 'Bar' => 44 })
end
it 'returns a bare configuration for a non-existing cop' do
expect(configuration.for_cop('Foo/Bar')).to eq({ 'Enabled' => true })
end
it 'returns the given configuration for a deprecated cop name' do
expect(configuration.for_cop('Lint/MovedCop')).to eq({ 'Bar' => 45 })
end
it 'maintains enabled status for a deprecated cop' do
expect(configuration.for_cop('Lint/OldCop')).to eq({ 'Bar' => 46, 'Enabled' => false })
end
it 'merges the deprecated name configuration and adds a warning for a renamed cop name' do
expect(configuration.for_cop('Lint/NewCop')).to eq(
{ 'Bar' => 46, 'Baz' => 1000, 'Enabled' => false }
)
expect($stderr.string.chomp).to eq(
'Warning: Using `Lint/OldCop` configuration in example/.rubocop.yml for `Lint/NewCop`.'
)
end
end
describe '#for_badge' do
let(:hash) do
{
'Style' => { 'Foo' => 42, 'Bar' => 666 },
'Layout/TrailingWhitespace' => { 'Bar' => 43 },
'Style/Alias' => { 'Bar' => 44 }
}
end
it 'takes into account the department' do
expect(configuration.for_badge(RuboCop::Cop::Style::Alias.badge)).to eq(
{ 'Enabled' => true,
'Foo' => 42,
'Bar' => 44 }
)
end
it 'works if department has no config' do
expect(configuration.for_badge(RuboCop::Cop::Layout::TrailingWhitespace.badge)).to eq(
{ 'Enabled' => true,
'Bar' => 43 }
)
end
end
describe '#for_enabled_cop' do
let(:hash) do
{
'Layout/TrailingWhitespace' => { 'Enabled' => true },
'Layout/LineLength' => { 'Enabled' => false },
'Metrics/MethodLength' => { 'Enabled' => 'pending' }
}
end
it 'returns config for an enabled cop' do
expect(configuration.for_enabled_cop('Layout/TrailingWhitespace')).to eq('Enabled' => true)
end
it 'returns an empty hash for a disabled cop' do
expect(configuration.for_enabled_cop('Layout/LineLength')).to be_empty
end
it 'returns config for an pending cop' do
expect(configuration.for_enabled_cop('Metrics/MethodLength')).to eq('Enabled' => 'pending')
end
end
describe '#cop_enabled?' do
let(:hash) do
{
'Layout/TrailingWhitespace' => { 'Enabled' => true },
'Layout/LineLength' => { 'Enabled' => false },
'Metrics/MethodLength' => { 'Enabled' => 'pending' }
}
end
it { is_expected.to be_cop_enabled('Layout/TrailingWhitespace') }
it { is_expected.not_to be_cop_enabled('Layout/LineLength') }
it { is_expected.to be_cop_enabled('Metrics/MethodLength') }
end
context 'whether the cop is enabled' do
def cop_enabled(cop_class)
configuration.for_cop(cop_class).fetch('Enabled')
end
context 'when an entire cop department is disabled' do
context 'but an individual cop is enabled' do
let(:hash) do
{
'Layout' => { 'Enabled' => false },
'Layout/TrailingWhitespace' => { 'Enabled' => true }
}
end
it 'the cop setting overrides the department' do
cop_class = RuboCop::Cop::Layout::TrailingWhitespace
expect(cop_enabled(cop_class)).to be true
end
end
end
context 'when a nested cop department is disabled' do
context 'but an individual cop is enabled' do
let(:hash) do
{
'Foo/Bar' => { 'Enabled' => false },
'Foo/Bar/BazCop' => { 'Enabled' => true }
}
end
it 'the cop setting overrides the department' do
cop_class = 'Foo/Bar/BazCop'
expect(cop_enabled(cop_class)).to be true
end
end
context 'and an individual cop is not specified' do
let(:hash) { { 'Foo/Bar' => { 'Enabled' => false } } }
it 'the cop setting overrides the department' do
cop_class = 'Foo/Bar/BazCop'
expect(cop_enabled(cop_class)).to be false
end
end
end
context 'when an entire cop department is enabled' do
context 'but an individual cop is disabled' do
let(:hash) do
{
'Style' => { 'Enabled' => true },
'Layout/TrailingWhitespace' => { 'Enabled' => false }
}
end
it 'still disables the cop' do
cop_class = RuboCop::Cop::Layout::TrailingWhitespace
expect(cop_enabled(cop_class)).to be false
end
end
end
context 'when a cop has configuration but no explicit Enabled setting' do
let(:hash) { { 'Layout/TrailingWhitespace' => { 'Exclude' => ['foo'] } } }
it 'enables the cop by default' do
cop_class = RuboCop::Cop::Layout::TrailingWhitespace
expect(cop_enabled(cop_class)).to be true
end
end
context 'when configuration has no mention of a cop' do
let(:hash) { {} }
it 'enables the cop that is not mentioned' do
expect(cop_enabled('VeryCustomDepartment/CustomCop')).to be true
end
context 'when all cops are disabled by default' do
let(:hash) { { 'AllCops' => { 'DisabledByDefault' => true } } }
it 'disables the cop that is not mentioned' do
expect(cop_enabled('VeryCustomDepartment/CustomCop')).to be false
end
end
context 'when all cops are explicitly enabled by default' do
let(:hash) { { 'AllCops' => { 'EnabledByDefault' => true } } }
it 'enables the cop that is not mentioned' do
expect(cop_enabled('VeryCustomDepartment/CustomCop')).to be true
end
end
end
end
describe '#gem_versions_in_target', :isolated_environment do
['Gemfile.lock', 'gems.locked'].each do |file_name|
let(:base_path) { configuration.base_dir_for_path_parameters }
let(:lockfile_path) { File.join(base_path, file_name) }
context "and #{file_name} exists" do
it 'returns the locked gem versions' do
content =
<<~LOCKFILE
GEM
remote: https://rubygems.org/
specs:
a (1.1.1)
b (2.2.2)
c (3.3.3)
d (4.4.4)
a (= 1.1.1)
b (>= 1.1.1, < 3.3.3)
c (~> 3.3)
PLATFORMS
ruby
DEPENDENCIES
rails (= 4.1.0)
BUNDLED WITH
2.4.19
LOCKFILE
expected = {
'a' => Gem::Version.new('1.1.1'),
'b' => Gem::Version.new('2.2.2'),
'c' => Gem::Version.new('3.3.3'),
'd' => Gem::Version.new('4.4.4')
}
create_file(lockfile_path, content)
expect(configuration.gem_versions_in_target).to eq expected
end
end
end
context 'and neither Gemfile.lock nor gems.locked exist' do
it 'returns nil' do
expect(configuration.gem_versions_in_target).to be_nil
end
end
end
describe '#target_rails_version', :isolated_environment do
let(:base_path) { configuration.base_dir_for_path_parameters }
let(:lockfile_path) { File.join(base_path, 'Gemfile.lock') }
context 'when bundler is loaded' do
context 'when a lockfile with railties exists' do
it 'returns the correct target rails version' do
content = <<~LOCKFILE
GEM
remote: https://rubygems.org/
specs:
rails (7.1.3.2)
railties (= 7.1.3.2)
railties (7.1.3.2)
DEPENDENCIES
rails (= 7.1.3.2)
LOCKFILE
create_file(lockfile_path, content)
expect(configuration.target_rails_version).to eq 7.1
end
end
context 'when a lockfile with railties from a prerelease exists' do
it 'returns the correct target rails version' do
content = <<~LOCKFILE
GEM
remote: https://rubygems.org/
specs:
rails (8.0.0.alpha)
railties (= 8.0.0.alpha)
railties (8.0.0.alpha)
DEPENDENCIES
rails (= 8.0.0.alpha)
LOCKFILE
create_file(lockfile_path, content)
expect(configuration.target_rails_version).to eq 8.0
end
end
end
context 'when bundler is not loaded' do
before { hide_const('Bundler') }
it 'falls back to the default rails version' do
content = <<~LOCKFILE
GEM
remote: https://rubygems.org/
specs:
rails (7.1.3.2)
railties (= 7.1.3.2)
railties (7.1.3.2)
DEPENDENCIES
rails (= 7.1.3.2)
LOCKFILE
create_file(lockfile_path, content)
expect(configuration.target_rails_version).to eq RuboCop::Config::DEFAULT_RAILS_VERSION
end
end
end
describe '#for_department', :restore_registry do
let(:hash) do
{
'Foo' => { 'Bar' => 42, 'Baz' => true },
'Foo/Foo' => { 'Bar' => 42, 'Qux' => true }
}
end
before { stub_cop_class('RuboCop::Foo::Foo') }
it "always returns the department's config" do
expect(configuration.for_department('Foo')).to eq hash['Foo']
end
it 'accepts a Symbol' do
expect(configuration.for_department(:Foo)).to eq hash['Foo']
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/path_util_spec.rb | spec/rubocop/path_util_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::PathUtil do
describe '#relative_path' do
it 'builds paths relative to PWD by default as a stop-gap' do
relative = File.join(Dir.pwd, 'relative')
expect(described_class.relative_path(relative)).to eq('relative')
end
it 'supports custom base paths' do
expect(described_class.relative_path('/foo/bar', '/foo')).to eq('bar')
end
if RuboCop::Platform.windows?
it 'works for different drives' do
expect(described_class.relative_path('D:/foo/bar', 'C:/foo')).to eq('D:/foo/bar')
end
it 'works for the same drive' do
expect(described_class.relative_path('D:/foo/bar', 'D:/foo')).to eq('bar')
end
end
end
describe '#absolute?' do
it 'returns a truthy value for a path beginning with slash' do
expect(described_class).to be_absolute('/Users/foo')
end
it 'returns a falsey value for a path beginning with a directory name' do
expect(described_class).not_to be_absolute('Users/foo')
end
if RuboCop::Platform.windows?
it 'returns a truthy value for a path beginning with an upper case drive letter' do
expect(described_class).to be_absolute('C:/Users/foo')
end
it 'returns a truthy value for a path beginning with a lower case drive letter' do
expect(described_class).to be_absolute('d:/Users/foo')
end
end
end
describe '#match_path?', :isolated_environment do
include FileHelper
before do
create_empty_file('file')
create_empty_file('dir/file')
create_empty_file('dir/files')
create_empty_file('dir/dir/file')
create_empty_file('dir/sub/file')
create_empty_file('dir/.hidden/file')
create_empty_file('dir/.hidden_file')
end
it 'does not match dir/** for file in hidden dir' do
expect(described_class).not_to be_match_path('dir/**', 'dir/.hidden/file')
end
it 'matches dir/** for hidden file' do
expect(described_class).to be_match_path('dir/**', 'dir/.hidden_file')
end
it 'does not match file in a subdirectory' do
expect(described_class).not_to be_match_path('file', 'dir/files')
expect(described_class).not_to be_match_path('dir', 'dir/file')
end
it 'matches strings to the full path' do
expect(described_class).to be_match_path("#{Dir.pwd}/dir/file", "#{Dir.pwd}/dir/file")
expect(described_class).not_to be_match_path(
"#{Dir.pwd}/dir/file",
"#{Dir.pwd}/dir/dir/file"
)
end
it 'matches glob expressions' do
expect(described_class).to be_match_path('dir/*', 'dir/file')
expect(described_class).to be_match_path('dir/**/*', 'dir/sub/file')
expect(described_class).to be_match_path('dir/**/*', 'dir/file')
expect(described_class).to be_match_path('**/*', 'dir/sub/file')
expect(described_class).to be_match_path('**/file', 'file')
expect(described_class).not_to be_match_path('sub/*', 'dir/sub/file')
expect(described_class).not_to be_match_path('**/*', 'dir/.hidden/file')
expect(described_class).to be_match_path('**/*', 'dir/.hidden_file')
expect(described_class).to be_match_path('**/.*/*', 'dir/.hidden/file')
expect(described_class).to be_match_path('**/.*', 'dir/.hidden_file')
expect(described_class).to be_match_path('c{at,ub}s', 'cats')
expect(described_class).to be_match_path('c{at,ub}s', 'cubs')
expect(described_class).not_to be_match_path('c{at,ub}s', 'gorillas')
expect(described_class).to be_match_path('**/*.{rb,txt}', 'dir/foo.txt')
end
it 'matches regexps' do
expect(described_class).to be_match_path(/^d.*e$/, 'dir/file')
expect(described_class).not_to be_match_path(/^d.*e$/, 'dir/filez')
end
it 'does not match invalid UTF-8 paths' do
expect(described_class).not_to be_match_path(/^d.*$/, "dir/file\xBF")
end
end
describe '.remote_file?' do
subject(:smart_path) { described_class.remote_file?(path) }
context 'when the path is an HTTP URL' do
let(:path) { 'http://example.com' }
it { is_expected.to be(true) }
end
context 'when the path is an HTTPS URL' do
let(:path) { 'https://example.com' }
it { is_expected.to be(true) }
end
context 'when the path is a relative path' do
let(:path) { './relative/path/to' }
it { is_expected.to be(false) }
end
context 'when path is an absolute path' do
let(:path) { '/absolute/path/to' }
it { is_expected.to be(false) }
end
end
describe '#smart_path', :isolated_environment do
subject(:smart_path) { described_class.smart_path(path) }
context 'when given a path relative to Dir.pwd' do
let(:path) { File.join(Dir.pwd, 'relative') }
it { is_expected.to eq('relative') }
end
context 'when given a path that is not relative to Dir.pwd' do
let(:path) { '/src/rubocop/foo' }
it { is_expected.to eq(path) }
end
context 'when given a RuboCop::RemoteConfig object' do
let(:uri) { 'https://www.example.com/rubocop.yml' }
let(:path) { RuboCop::RemoteConfig.new(uri, Dir.pwd) }
it { is_expected.to eq(uri) }
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/options_spec.rb | spec/rubocop/options_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Options, :isolated_environment do
include FileHelper
subject(:options) { described_class.new }
include_context 'mock console output'
def abs(path)
File.expand_path(path)
end
describe 'option' do
describe '-h/--help' do
# HACK: `help` option is implemented with OptionParser, if the environment vars
# `RUBY_PAGER` or `PAGER` are set, the mock for stdout will not be applied.
# To ensure stdout is mocked, a simple way is to temporarily delete these environment vars.
# https://github.com/ruby/optparse/blob/v0.6.0/lib/optparse.rb#L1053-L1071
around do |example|
original_ruby_pager = ENV.delete('RUBY_PAGER')
original_pager = ENV.delete('PAGER')
begin
example.run
ensure
ENV['RUBY_PAGER'] = original_ruby_pager
ENV['PAGER'] = original_pager
end
end
it 'exits cleanly `-h`' do
expect { options.parse ['-h'] }.to exit_with_code(0)
end
it 'exits cleanly `--help`' do
expect { options.parse ['--help'] }.to exit_with_code(0)
end
# rubocop:disable RSpec/ExampleLength
it 'shows help text' do
begin
options.parse(['--help'])
rescue SystemExit # rubocop:disable Lint/SuppressedException
end
# rubocop:todo Naming/InclusiveLanguage
expected_help = <<~OUTPUT
Usage: rubocop [options] [file1, file2, ...]
Basic Options:
-l, --lint Run only lint cops.
-x, --fix-layout Run only layout cops, with autocorrect on.
--safe Run only safe cops.
--except [COP1,COP2,...] Exclude the given cop(s).
--only [COP1,COP2,...] Run only the given cop(s).
--only-guide-cops Run only cops for rules that link to a
style guide.
-F, --fail-fast Inspect files in order of modification
time and stop after the first file
containing offenses.
--disable-pending-cops Run without pending cops.
--enable-pending-cops Run with pending cops.
--ignore-disable-comments Report offenses even if they have been manually disabled
with a `rubocop:disable` or `rubocop:todo` directive.
--force-exclusion Any files excluded by `Exclude` in configuration
files will be excluded, even if given explicitly
as arguments.
--only-recognized-file-types Inspect files given on the command line only if
they are listed in `AllCops/Include` parameters
of user configuration or default configuration.
--ignore-parent-exclusion Prevent from inheriting `AllCops/Exclude` from
parent folders.
--ignore-unrecognized-cops Ignore unrecognized cops or departments in the config.
--force-default-config Use default configuration even if configuration
files are present in the directory tree.
-s, --stdin FILE Pipe source from STDIN, using FILE in offense
reports. This is useful for editor integration.
--editor-mode Optimize real-time feedback in editors,
adjusting behaviors for editing experience.
-P, --[no-]parallel Use available CPUs to execute inspection in
parallel. Default is true.
You can specify the number of parallel processes using
the $PARALLEL_PROCESSOR_COUNT environment variable.
--raise-cop-error Raise cop-related errors with cause and location.
This is used to prevent cops from failing silently.
Default is false.
--fail-level SEVERITY Minimum severity for exit with error code.
[A] autocorrect
[I] info
[R] refactor
[C] convention
[W] warning
[E] error
[F] fatal
Caching:
-C, --cache FLAG Use result caching (FLAG=true) or don't
(FLAG=false), default determined by
configuration parameter AllCops: UseCache.
--cache-root DIR Set the cache root directory.
Takes precedence over the configuration
parameter AllCops: CacheRootDirectory and
the $RUBOCOP_CACHE_ROOT environment variable.
LSP Option:
--lsp Start a language server listening on STDIN.
Server Options:
--[no-]server If a server process has not been started yet, start
the server process and execute inspection with server.
Default is false.
You can specify the server host and port with the
$RUBOCOP_SERVER_HOST and the $RUBOCOP_SERVER_PORT
environment variables.
--restart-server Restart server process.
--start-server Start server process.
--stop-server Stop server process.
--server-status Show server status.
--no-detach Run the server process in the foreground.
Output Options:
-f, --format FORMATTER Choose an output formatter. This option
can be specified multiple times to enable
multiple formatters at the same time.
[a]utogenconf
[c]lang
[e]macs
[fi]les
[fu]ubar
[g]ithub
[h]tml
[j]son
[ju]nit
[m]arkdown
[o]ffenses
[pa]cman
[p]rogress (default)
[q]uiet
[s]imple
[t]ap
[w]orst
custom formatter class name
-D, --[no-]display-cop-names Display cop names in offense messages.
Default is true.
-E, --extra-details Display extra details in offense messages.
-S, --display-style-guide Display style guide URLs in offense messages.
-o, --out FILE Write output to a file instead of STDOUT.
This option applies to the previously
specified --format, or the default format
if no format is specified.
--stderr Write all output to stderr except for the
autocorrected source. This is especially useful
when combined with --autocorrect and --stdin.
--display-time Display elapsed time in seconds.
--display-only-failed Only output offense messages. Omit passing
cops. Only valid for --format junit.
--display-only-fail-level-offenses
Only output offense messages at
the specified --fail-level or above.
--display-only-correctable Only output correctable offense messages.
--display-only-safe-correctable
Only output safe-correctable offense messages
when combined with --display-only-correctable.
Autocorrection:
-a, --autocorrect Autocorrect offenses (only when it's safe).
--auto-correct (same, deprecated)
--safe-auto-correct (same, deprecated)
-A, --autocorrect-all Autocorrect offenses (safe and unsafe).
--auto-correct-all (same, deprecated)
--disable-uncorrectable Used with --autocorrect to annotate any
offenses that do not support autocorrect
with `rubocop:todo` comments.
Config Generation:
--auto-gen-config Generate a configuration file acting as a
TODO list.
--regenerate-todo Regenerate the TODO configuration file using
the last configuration. If there is no existing
TODO file, acts like --auto-gen-config.
--exclude-limit COUNT Set the limit for how many files to explicitly exclude.
If there are more files than the limit, the cop will
be disabled instead. Default is 15.
--no-exclude-limit Do not set the limit for how many files to exclude.
--[no-]offense-counts Include offense counts in configuration
file generated by --auto-gen-config.
Default is true.
--[no-]auto-gen-only-exclude Generate only Exclude parameters and not Max
when running --auto-gen-config, except if the
number of files with offenses is bigger than
exclude-limit. Default is false.
--[no-]auto-gen-timestamp Include the date and time when the --auto-gen-config
was run in the file it generates. Default is true.
--[no-]auto-gen-enforced-style
Add a setting to the TODO configuration file to enforce
the style used, rather than a per-file exclusion
if one style is used in all files for cop with
EnforcedStyle as a configurable option
when the --auto-gen-config was run
in the file it generates. Default is true.
Additional Modes:
-L, --list-target-files List all files RuboCop will inspect.
--show-cops [COP1,COP2,...] Shows the given cops, or all cops by
default, and their configurations for the
current directory.
You can use `*` as a wildcard.
--show-docs-url [COP1,COP2,...]
Display url to documentation for the given
cops, or base url by default.
General Options:
--init Generate a .rubocop.yml file in the current directory.
-c, --config FILE Specify configuration file.
-d, --debug Display debug info.
--plugin FILE Load a RuboCop plugin.
-r, --require FILE Require Ruby file.
--[no-]color Force color output on or off.
-v, --version Display version.
-V, --verbose-version Display verbose version.
OUTPUT
# rubocop:enable Naming/InclusiveLanguage
if RUBY_ENGINE == 'ruby' && !RuboCop::Platform.windows?
expected_help += <<~OUTPUT
Profiling Options:
--profile Profile rubocop.
--memory Profile rubocop memory usage.
OUTPUT
end
expect($stdout.string).to eq(expected_help)
end
# rubocop:enable RSpec/ExampleLength
it 'lists all builtin formatters' do
begin
options.parse(['--help'])
rescue SystemExit # rubocop:disable Lint/SuppressedException
end
option_sections = $stdout.string.lines.slice_before(/^\s*-/)
format_section = option_sections.find { |lines| /^\s*-f/.match?(lines.first) }
formatter_keys = format_section.reduce([]) do |keys, line|
match = line.match(/^ {39}(\[[a-z\]]+)/)
next keys unless match
keys << match.captures.first
end.sort
expected_formatter_keys =
RuboCop::Formatter::FormatterSet::BUILTIN_FORMATTERS_FOR_KEYS.keys.sort
expect(formatter_keys).to eq(expected_formatter_keys)
end
end
describe 'incompatible cli options' do
it 'rejects using -v with -V' do
msg = 'Incompatible cli options: [:version, :verbose_version]'
expect { options.parse %w[-vV] }.to raise_error(RuboCop::OptionArgumentError, msg)
end
it 'rejects using -v with --show-cops' do
msg = 'Incompatible cli options: [:version, :show_cops]'
expect { options.parse %w[-v --show-cops] }
.to raise_error(RuboCop::OptionArgumentError, msg)
end
it 'rejects using -V with --show-cops' do
msg = 'Incompatible cli options: [:verbose_version, :show_cops]'
expect { options.parse %w[-V --show-cops] }
.to raise_error(RuboCop::OptionArgumentError, msg)
end
it 'rejects using `--lsp` with `--editor-mode`' do
msg = 'Do not specify `--editor-mode` as it is redundant in `--lsp`.'
expect do
options.parse %w[--lsp --editor-mode]
end.to raise_error(RuboCop::OptionArgumentError, msg)
end
it 'mentions all incompatible options when more than two are used' do
msg = 'Incompatible cli options: [:version, :verbose_version, :show_cops]'
expect { options.parse %w[-vV --show-cops] }
.to raise_error(RuboCop::OptionArgumentError, msg)
end
end
describe '--fix-layout' do
it 'sets some autocorrect options' do
options.parse %w[--fix-layout]
expect_autocorrect_options_for_fix_layout
end
end
describe '--parallel' do
context 'combined with --cache false' do
it 'ignores --parallel' do
msg = '-P/--parallel is being ignored because it is not compatible with --cache false'
options.parse %w[--parallel --cache false]
expect($stdout.string).to include(msg)
expect(options.instance_variable_get(:@options)).not_to be_key(:parallel)
end
end
context 'combined with an autocorrect argument' do
context 'combined with --fix-layout' do
it 'allows --parallel' do
options.parse %w[--parallel --fix-layout]
expect($stdout.string).not_to include('-P/--parallel is being ignored')
expect(options.instance_variable_get(:@options)).to be_key(:parallel)
end
end
context 'combined with --autocorrect' do
it 'allows --parallel' do
options.parse %w[--parallel --autocorrect]
expect($stdout.string).not_to include('-P/--parallel is being ignored')
expect(options.instance_variable_get(:@options)).to be_key(:parallel)
end
end
context 'combined with --autocorrect-all' do
it 'allows --parallel' do
options.parse %w[--parallel --autocorrect-all]
expect($stdout.string).not_to include('-P/--parallel is being ignored')
expect(options.instance_variable_get(:@options)).to be_key(:parallel)
end
end
end
context 'combined with --auto-gen-config' do
it 'ignores --parallel' do
msg = '-P/--parallel is being ignored because it is not compatible with --auto-gen-config'
options.parse %w[--parallel --auto-gen-config]
expect($stdout.string).to include(msg)
expect(options.instance_variable_get(:@options)).not_to be_key(:parallel)
end
end
context 'combined with --fail-fast' do
it 'ignores --parallel' do
msg = '-P/--parallel is being ignored because it is not compatible with -F/--fail-fast'
options.parse %w[--parallel --fail-fast]
expect($stdout.string).to include(msg)
expect(options.instance_variable_get(:@options)).not_to be_key(:parallel)
end
end
context 'combined with two incompatible arguments' do
it 'ignores --parallel and lists both incompatible arguments' do
options.parse %w[--parallel --fail-fast --autocorrect]
expect($stdout.string).to include('-P/--parallel is being ignored because it is not ' \
'compatible with -F/--fail-fast')
expect(options.instance_variable_get(:@options)).not_to be_key(:parallel)
end
end
end
describe '--no-parallel' do
it 'disables parallel from file' do
results = options.parse %w[--no-parallel]
expect(results).to eq([{ parallel: false }, []])
end
end
describe '--display-only-failed' do
it 'fails if given without --format junit' do
expect { options.parse %w[--display-only-failed] }
.to raise_error(RuboCop::OptionArgumentError)
end
it 'works if given with --format junit' do
expect { options.parse %w[--format junit --display-only-failed] }
.not_to raise_error(RuboCop::OptionArgumentError)
end
end
describe '--display-only-fail-level-offenses' do
%w[--fix-layout -x --autocorrect -a --autocorrect-all -A].each do |o|
it 'fails if given with an autocorrect argument' do
expect { options.parse ['--display-only-fail-level-offenses', o] }
.not_to raise_error(RuboCop::OptionArgumentError)
end
end
end
describe '--display-only-correctable' do
it 'fails if given with --display-only-failed' do
expect { options.parse %w[--display-only-correctable --display-only-failed] }
.to raise_error(RuboCop::OptionArgumentError)
end
it 'fails if given with an autocorrect argument' do
%w[--fix-layout -x --autocorrect -a --autocorrect-all -A].each do |o|
expect { options.parse ['--display-only-correctable', o] }
.to raise_error(RuboCop::OptionArgumentError)
end
end
end
describe '--fail-level' do
it 'accepts full severity names' do
%w[info refactor convention warning error fatal].each do |severity|
expect { options.parse(['--fail-level', severity]) }.not_to raise_error
end
end
it 'accepts severity initial letters' do
%w[I R C W E F].each do |severity|
expect { options.parse(['--fail-level', severity]) }.not_to raise_error
end
end
it 'accepts the "fake" severities A/autocorrect' do
%w[autocorrect A].each do |severity|
expect { options.parse(['--fail-level', severity]) }.not_to raise_error
end
end
end
describe '--raise-cop-error' do
it 'raises cop errors' do
results = options.parse %w[--raise-cop-error]
expect(results).to eq([{ raise_cop_error: true }, []])
end
end
describe '--require' do
let(:required_file_path) { './path/to/required_file.rb' }
before do
create_empty_file('example.rb')
create_file(required_file_path, "puts 'Hello from required file!'")
end
it 'requires the passed path' do
options.parse(['--require', required_file_path, 'example.rb'])
expect($stdout.string).to start_with('Hello from required file!')
end
end
describe '--cache' do
it 'fails if no argument is given' do
expect { options.parse %w[--cache] }.to raise_error(OptionParser::MissingArgument)
end
it 'fails if unrecognized argument is given' do
expect { options.parse %w[--cache maybe] }.to raise_error(RuboCop::OptionArgumentError)
end
it 'accepts true as argument' do
expect { options.parse %w[--cache true] }.not_to raise_error
end
it 'accepts false as argument' do
expect { options.parse %w[--cache false] }.not_to raise_error
end
end
describe '--cache-root' do
it 'fails if no argument is given' do
expect { options.parse %w[--cache-root] }.to raise_error(OptionParser::MissingArgument)
end
it 'fails if also `--cache false` is given' do
expect { options.parse %w[--cache false --cache-root /some/dir] }
.to raise_error(RuboCop::OptionArgumentError)
end
it 'accepts a path as argument' do
expect { options.parse %w[--cache-root /some/dir] }.not_to raise_error
end
end
describe '--disable-uncorrectable' do
it 'accepts together with a safe autocorrect argument' do
%w[--fix-layout -x --autocorrect -a].each do |o|
expect { options.parse ['--disable-uncorrectable', o] }.not_to raise_error
end
end
it 'accepts together with an unsafe autocorrect argument' do
%w[--fix-layout -x --autocorrect-all -A].each do |o|
expect { options.parse ['--disable-uncorrectable', o] }.not_to raise_error
end
end
it 'fails if given without an autocorrect argument' do
expect { options.parse %w[--disable-uncorrectable] }
.to raise_error(RuboCop::OptionArgumentError)
end
end
describe '--exclude-limit' do
it 'fails if given last without argument' do
expect { options.parse %w[--auto-gen-config --exclude-limit] }
.to raise_error(OptionParser::MissingArgument)
end
it 'fails if given alone without argument' do
expect do
options.parse %w[--exclude-limit]
end.to raise_error(OptionParser::MissingArgument)
end
it 'fails if given first without argument' do
expect { options.parse %w[--exclude-limit --auto-gen-config] }
.to raise_error(OptionParser::MissingArgument)
end
it 'fails if given without --auto-gen-config' do
expect do
options.parse %w[--exclude-limit 10]
end.to raise_error(RuboCop::OptionArgumentError)
end
end
describe '--autocorrect' do
context 'Specify only --autocorrect' do
it 'sets some autocorrect options' do
options.parse %w[--autocorrect]
expect_autocorrect_options_for_autocorrect
end
end
context 'Specify --autocorrect and --autocorrect-all' do
it 'emits a warning and sets some autocorrect options' do
expect { options.parse %w[--autocorrect --autocorrect-all] }.to raise_error(
RuboCop::OptionArgumentError,
/Error: Both safe and unsafe autocorrect options are specified, use only one./
)
end
end
end
describe '--autocorrect-all' do
it 'sets some autocorrect options' do
options.parse %w[--autocorrect-all]
expect_autocorrect_options_for_autocorrect_all
end
end
describe '--auto-gen-only-exclude' do
it 'fails if given without --auto-gen-config' do
expect { options.parse %w[--auto-gen-only-exclude] }
.to raise_error(RuboCop::OptionArgumentError)
end
end
describe '--auto-gen-config' do
it 'accepts other options' do
expect { options.parse %w[--auto-gen-config --lint] }.not_to raise_error
end
end
describe '--regenerate-todo' do
subject(:parsed_options) { options.parse(command_line_options).first }
let(:config_regeneration) do
instance_double(RuboCop::ConfigRegeneration, options: todo_options)
end
let(:todo_options) do
{ auto_gen_config: true, exclude_limit: '100', offense_counts: false }
end
before do
allow(RuboCop::ConfigRegeneration).to receive(:new).and_return(config_regeneration)
end
context 'when no other options are given' do
let(:command_line_options) { %w[--regenerate-todo] }
let(:expected_options) do
{
auto_gen_config: true,
exclude_limit: '100',
offense_counts: false,
regenerate_todo: true
}
end
it { is_expected.to eq(expected_options) }
end
context 'when todo options are overridden before --regenerate-todo' do
let(:command_line_options) { %w[--exclude-limit 50 --regenerate-todo] }
let(:expected_options) do
{
auto_gen_config: true,
exclude_limit: '50',
offense_counts: false,
regenerate_todo: true
}
end
it { is_expected.to eq(expected_options) }
end
context 'when todo options are overridden after --regenerate-todo' do
let(:command_line_options) { %w[--regenerate-todo --exclude-limit 50] }
let(:expected_options) do
{
auto_gen_config: true,
exclude_limit: '50',
offense_counts: false,
regenerate_todo: true
}
end
it { is_expected.to eq(expected_options) }
end
context 'when disabled options are overridden to be enabled' do
let(:command_line_options) { %w[--regenerate-todo --offense-counts] }
let(:expected_options) do
{
auto_gen_config: true,
exclude_limit: '100',
offense_counts: true,
regenerate_todo: true
}
end
it { is_expected.to eq(expected_options) }
end
end
describe '-s/--stdin' do
before do
$stdin = StringIO.new
$stdin.puts("{ foo: 'bar' }")
$stdin.rewind
end
it 'fails if no paths are given' do
expect { options.parse %w[-s] }.to raise_error(OptionParser::MissingArgument)
end
it 'succeeds with exactly one path' do
expect { options.parse %w[--stdin foo] }.not_to raise_error
end
it 'fails if more than one path is given' do
expect do
options.parse %w[--stdin foo bar]
end.to raise_error(RuboCop::OptionArgumentError)
end
end
# rubocop:todo Naming/InclusiveLanguage
describe 'deprecated options' do
describe '--auto-correct' do
it 'emits a warning and sets the correct options instead' do
options.parse %w[--auto-correct]
expect($stderr.string).to include('--auto-correct is deprecated; use --autocorrect')
expect(options.instance_variable_get(:@options)).not_to be_key(:auto_correct)
expect_autocorrect_options_for_autocorrect
end
end
describe '--safe-auto-correct' do
it 'emits a warning and sets the correct options instead' do
options.parse %w[--safe-auto-correct]
expect($stderr.string).to include('--safe-auto-correct is deprecated; use --autocorrect')
expect(options.instance_variable_get(:@options)).not_to be_key(:safe_auto_correct)
expect_autocorrect_options_for_autocorrect
end
end
describe '--auto-correct-all' do
it 'emits a warning and sets the correct options instead' do
options.parse %w[--auto-correct-all]
expect($stderr.string).to include('--auto-correct-all is deprecated; ' \
'use --autocorrect-all')
expect(options.instance_variable_get(:@options)).not_to be_key(:auto_correct_all)
expect_autocorrect_options_for_autocorrect_all
end
end
end
# rubocop:enable Naming/InclusiveLanguage
def expect_autocorrect_options_for_fix_layout
options_keys = options.instance_variable_get(:@options).keys
expect(options_keys).to include(:fix_layout)
expect(options_keys).to include(:autocorrect)
expect(options_keys).not_to include(:safe_autocorrect)
expect(options_keys).not_to include(:autocorrect_all)
end
def expect_autocorrect_options_for_autocorrect
options_keys = options.instance_variable_get(:@options).keys
expect(options_keys).not_to include(:fix_layout)
expect(options_keys).to include(:autocorrect)
expect(options_keys).to include(:safe_autocorrect)
expect(options_keys).not_to include(:autocorrect_all)
end
def expect_autocorrect_options_for_autocorrect_all
options_keys = options.instance_variable_get(:@options).keys
expect(options_keys).not_to include(:fix_layout)
expect(options_keys).to include(:autocorrect)
expect(options_keys).not_to include(:safe_autocorrect)
expect(options_keys).to include(:autocorrect_all)
end
end
describe 'options precedence' do
def with_env_options(options)
ENV['RUBOCOP_OPTS'] = options
yield
ensure
ENV.delete('RUBOCOP_OPTS')
end
subject(:parsed_options) { options.parse(command_line_options).first }
let(:command_line_options) { %w[--no-color] }
describe '.rubocop file' do
before { create_file('.rubocop', '--color --fail-level C') }
it 'has lower precedence then command line options' do
expect(parsed_options).to eq(color: false, fail_level: :convention)
end
it 'has lower precedence then options from RUBOCOP_OPTS env variable' do
with_env_options '--fail-level W' do
expect(parsed_options).to eq(color: false, fail_level: :warning)
end
end
end
describe '.rubocop directory' do
before { FileUtils.mkdir '.rubocop' }
it 'is ignored and command line options are used' do
expect(parsed_options).to eq(color: false)
end
end
context 'RUBOCOP_OPTS environment variable' do
it 'has lower precedence then command line options' do
with_env_options '--color' do
expect(parsed_options).to eq(color: false)
end
end
it 'has higher precedence then options from .rubocop file' do
create_file('.rubocop', '--color --fail-level C')
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/intentionally_empty_file.rb | spec/rubocop/intentionally_empty_file.rb | ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false | |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/rspec/expect_offense_spec.rb | spec/rubocop/rspec/expect_offense_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::RSpec::ExpectOffense, :config do
context 'with a cop that loops during autocorrection' do
let(:cop_class) { RuboCop::Cop::Test::InfiniteLoopDuringAutocorrectCop }
it '`expect_no_corrections` raises' do
expect_offense(<<~RUBY)
class Test
^^^^^^^^^^ Class must be a Module
end
RUBY
expect { expect_no_corrections }.to raise_error(RuboCop::Runner::InfiniteCorrectionLoop)
end
end
context 'with a cop that loops after autocorrecting something' do
let(:cop_class) { RuboCop::Cop::Test::InfiniteLoopDuringAutocorrectWithChangeCop }
it '`expect_correction` raises' do
expect_offense(<<~RUBY)
class Test
^^^^^^^^^^ Class must be a Module
end
RUBY
expect do
expect_correction(<<~RUBY)
module Test
end
RUBY
end.to raise_error(RuboCop::Runner::InfiniteCorrectionLoop)
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/plugin/loader_spec.rb | spec/rubocop/plugin/loader_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Plugin::Loader do
describe '.load' do
subject(:plugins) { described_class.load(plugin_configs) }
context 'when plugin config is a string' do
let(:plugin_configs) { ['rubocop/cop/internal_affairs'] }
let(:plugin) { plugins.first }
it 'returns an instance of plugin' do
expect(plugin).to be_an_instance_of(RuboCop::InternalAffairs::Plugin)
end
describe 'about' do
let(:about) { plugin.about }
it 'has plugin name' do
expect(plugin.about.name).to eq 'rubocop-internal_affairs'
end
end
describe 'rules' do
let(:runner_context) { LintRoller::Context.new }
let(:rules) { plugin.rules(runner_context) }
it 'has plugin configuration path' do
expect(rules.value.to_s).to end_with 'config/internal_affairs.yml'
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/plugin/configuration_integrator_spec.rb | spec/rubocop/plugin/configuration_integrator_spec.rb | # frozen_string_literal: true
require 'lint_roller'
RSpec.describe RuboCop::Plugin::ConfigurationIntegrator, :isolated_environment do
include FileHelper
describe '.integrate_plugins_into_rubocop_config' do
subject(:integrated_config) do
described_class.integrate_plugins_into_rubocop_config(rubocop_config, plugins)
end
after do
default_configuration = RuboCop::ConfigLoader.default_configuration
default_configuration.delete('inherit_mode')
RuboCop::ConfigLoader.instance_variable_set(:@default_configuration, default_configuration)
end
context 'when using internal plugin' do
let(:rubocop_config) { RuboCop::Config.new }
let(:plugins) { RuboCop::Plugin::Loader.load(['rubocop/cop/internal_affairs']) }
it 'integrates base cops' do
expect(rubocop_config.to_h['Style/HashSyntax']['SupportedStyles']).to eq(
%w[ruby19 hash_rockets no_mixed_keys ruby19_no_mixed_keys]
)
end
it 'integrates plugin cops' do
expect(integrated_config.to_h['InternalAffairs/CopDescription']).to eq(
{ 'Include' => ['lib/rubocop/cop/**/*.rb'] }
)
end
end
context 'when using a plugin with `Plugin` type is `:path`' do
let(:rubocop_config) do
RuboCop::Config.new
end
let(:fake_plugin) do
Class.new(LintRoller::Plugin) do
def rules(_context)
LintRoller::Rules.new(type: :path, config_format: :rubocop, value: 'default.yml')
end
end
end
let(:plugins) { [fake_plugin.new] }
let(:all_cops_exclude) { integrated_config.to_h['AllCops']['Exclude'] }
before do
create_file('default.yml', <<~YAML)
AllCops:
Exclude:
- db/*schema.rb
YAML
end
it 'integrates `Exclude` values from plugin cops as absolute paths into the configuration' do
expect(all_cops_exclude.count).to eq 5
expect(all_cops_exclude.last).to end_with('/db/*schema.rb')
end
end
context 'when using a plugin with `Plugin` type is `:object`' do
let(:rubocop_config) do
RuboCop::Config.new('Style/FrozenStringLiteralComment' => { 'Exclude' => %w[**/*.arb] })
end
let(:fake_plugin) do
Class.new(LintRoller::Plugin) do
def rules(_context)
LintRoller::Rules.new(
type: :object,
config_format: :rubocop,
value: {
'inherit_mode' => {
'merge' => ['Exclude']
},
'Style/FrozenStringLiteralComment' => {
'Exclude' => %w[**/*.erb]
}
}
)
end
end
end
let(:plugins) { [fake_plugin.new] }
let(:exclude) { integrated_config.to_h['Style/FrozenStringLiteralComment']['Exclude'] }
it 'integrates `Exclude` values from plugin cops into the configuration' do
expect(exclude.count).to eq 2
expect(exclude[0]).to end_with('.arb')
expect(exclude[1]).to end_with('.erb')
end
end
context 'when using a plugin with an unsupported RuboCop engine' do
let(:rubocop_config) do
RuboCop::Config.new
end
let(:unsupported_plugin) do
Class.new(LintRoller::Plugin) do
def supported?(context)
context.engine == :not_rubocop
end
end
end
let(:plugins) { [unsupported_plugin.new] }
it 'raises `RuboCop::Plugin::NotSupportedError`' do
expect { integrated_config }.to raise_error(RuboCop::Plugin::NotSupportedError)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/lsp/server_spec.rb | spec/rubocop/lsp/server_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::LSP::Server, :isolated_environment do
include LSPHelper
subject(:result) { run_server_on_requests(*requests) }
after do
RuboCop::LSP.disable
end
let(:messages) { result[0] }
let(:stderr) { result[1].string }
let(:eol) do
if RuboCop::Platform.windows?
"\r\n"
else
"\n"
end
end
include_context 'cli spec behavior'
describe 'server initializes and responds with proper capabilities' do
let(:requests) do
[
jsonrpc: '2.0',
id: 2,
method: 'initialize',
params: { probably: "Don't need real params for this test?" }
]
end
it 'handles requests' do
expect(stderr).to eq('')
expect(messages.count).to eq(1)
expect(messages.first).to eq(
jsonrpc: '2.0',
id: 2,
result: {
capabilities: {
textDocumentSync: { openClose: true, change: 2 },
documentFormattingProvider: true
}
}
)
end
end
describe 'did open' do
let(:requests) do
[
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: "def hi#{eol} [1, 2,#{eol} 3 ]#{eol}end#{eol}",
uri: 'file:///path/to/file.rb',
version: 0
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
expect(messages.count).to eq(1)
expect(messages.first).to eq(
jsonrpc: '2.0',
method: 'textDocument/publishDiagnostics',
params: {
diagnostics: [
{
code: 'Style/FrozenStringLiteralComment',
codeDescription: {
href: 'https://docs.rubocop.org/rubocop/cops_style.html#stylefrozenstringliteralcomment'
},
data: {
code_actions: [
{
edit: {
documentChanges: [
edits: [
{
newText: "# frozen_string_literal: true\n",
range: {
start: { character: 0, line: 0 },
end: { character: 0, line: 0 }
}
}
],
textDocument: { uri: 'file:///path/to/file.rb', version: nil }
]
},
kind: 'quickfix',
title: 'Autocorrect Style/FrozenStringLiteralComment',
isPreferred: true
}, {
edit: {
documentChanges: [
edits: [
{
newText: ' # rubocop:disable Style/FrozenStringLiteralComment',
range: {
start: { character: 6, line: 0 },
end: { character: 6, line: 0 }
}
}
],
textDocument: { uri: 'file:///path/to/file.rb', version: nil }
]
},
kind: 'quickfix',
title: 'Disable Style/FrozenStringLiteralComment for this line'
}
],
correctable: true
},
message: 'Style/FrozenStringLiteralComment: Missing frozen string literal comment.',
range: {
start: { character: 0, line: 0 },
end: { character: 1, line: 0 }
},
severity: 3,
source: 'RuboCop'
}, {
code: 'Layout/SpaceInsideArrayLiteralBrackets',
codeDescription: {
href: 'https://docs.rubocop.org/rubocop/cops_layout.html#layoutspaceinsidearrayliteralbrackets'
},
data: {
code_actions: [
{
edit: {
documentChanges: [
edits: [
newText: '', range: {
end: { character: 6, line: 2 },
start: { character: 4, line: 2 }
}
],
textDocument: { uri: 'file:///path/to/file.rb', version: nil }
]
},
kind: 'quickfix',
title: 'Autocorrect Layout/SpaceInsideArrayLiteralBrackets',
isPreferred: true
}, {
edit: {
documentChanges: [
edits: [
newText: ' # rubocop:disable Layout/SpaceInsideArrayLiteralBrackets',
range: {
end: { character: 7, line: 2 },
start: {
character: 7, line: 2
}
}
],
textDocument: { uri: 'file:///path/to/file.rb', version: nil }
]
},
kind: 'quickfix',
title: 'Disable Layout/SpaceInsideArrayLiteralBrackets for this line'
}
],
correctable: true
},
message: 'Layout/SpaceInsideArrayLiteralBrackets: Do not use space inside array brackets.', # rubocop:disable Layout/LineLength
range: {
start: { character: 4, line: 2 },
end: { character: 6, line: 2 }
},
severity: 3,
source: 'RuboCop'
}
], uri: 'file:///path/to/file.rb'
}
)
end
end
describe 'did open with multibyte character(utf-16)' do
let(:requests) do
[
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: "'βπ£πΊ' x",
uri: 'file:///path/to/file.rb',
version: 0
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
expect(messages.count).to eq(1)
expect(messages.first).to eq(
jsonrpc: '2.0',
method: 'textDocument/publishDiagnostics',
params: {
diagnostics: [
{
code: 'Lint/Syntax',
codeDescription: {
href: 'https://docs.rubocop.org/rubocop/cops_lint.html#lintsyntax'
},
data: {
code_actions: [
{
edit: {
documentChanges: [
{
edits: [
{
newText: ' # rubocop:disable Lint/Syntax',
range: {
start: { character: 9, line: 0 },
end: { character: 9, line: 0 }
}
}
],
textDocument: { uri: 'file:///path/to/file.rb', version: nil }
}
]
},
kind: 'quickfix',
title: 'Disable Lint/Syntax for this line'
}
],
correctable: false
},
message: "Lint/Syntax: unexpected token tIDENTIFIER\n\nThis offense is not autocorrectable.\n", # rubocop:disable Layout/LineLength
range: {
start: { character: 8, line: 0 },
end: { character: 9, line: 0 }
},
severity: 1,
source: 'RuboCop'
}
],
uri: 'file:///path/to/file.rb'
}
)
end
end
describe 'format by default (safe autocorrect)' do
let(:requests) do
[
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: "puts 'hi'",
uri: 'file:///path/to/file.rb',
version: 0
}
}
}, {
jsonrpc: '2.0',
method: 'textDocument/didChange',
params: {
contentChanges: [{ text: "puts 'bye'" }],
textDocument: {
uri: 'file:///path/to/file.rb',
version: 10
}
}
}, {
jsonrpc: '2.0',
id: 20,
method: 'textDocument/formatting',
params: {
options: { insertSpaces: true, tabSize: 2 },
textDocument: { uri: 'file:///path/to/file.rb' }
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
format_result = messages.last
expect(format_result).to eq(
jsonrpc: '2.0',
id: 20,
result: [
newText: "puts 'bye'\n",
range: {
start: { line: 0, character: 0 }, end: { line: 1, character: 0 }
}
]
)
end
end
describe 'format by default (safe autocorrect) with an `AutoCorrect: contextual` cop' do
let(:empty_comment) { "##{eol}" }
let(:requests) do
[
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: empty_comment,
uri: 'file:///path/to/file.rb',
version: 0
}
}
}, {
jsonrpc: '2.0',
method: 'textDocument/didChange',
params: {
contentChanges: [{ text: empty_comment }],
textDocument: {
uri: 'file:///path/to/file.rb',
version: 10
}
}
}, {
jsonrpc: '2.0',
id: 20,
method: 'textDocument/formatting',
params: {
options: { insertSpaces: true, tabSize: 2 },
textDocument: { uri: 'file:///path/to/file.rb' }
}
}
]
end
it 'handles requests, but does not autocorrect with `Layout/EmptyComment` as an `AutoCorrect: contextual` cop' do
expect(stderr).to eq('')
format_result = messages.last
expect(format_result).to eq(jsonrpc: '2.0', id: 20, result: [])
end
end
describe 'format with `safeAutocorrect: true`' do
let(:requests) do
[
{
jsonrpc: '2.0',
id: 2,
method: 'initialize',
params: {
probably: "Don't need real params for this test?",
initializationOptions: {
safeAutocorrect: true
}
}
},
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: "puts 'hi'",
uri: 'file:///path/to/file.rb',
version: 0
}
}
}, {
jsonrpc: '2.0',
method: 'textDocument/didChange',
params: {
contentChanges: [{ text: "puts 'bye'" }],
textDocument: {
uri: 'file:///path/to/file.rb',
version: 10
}
}
}, {
jsonrpc: '2.0',
id: 20,
method: 'textDocument/formatting',
params: {
options: { insertSpaces: true, tabSize: 2 },
textDocument: { uri: 'file:///path/to/file.rb' }
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
format_result = messages.last
expect(format_result).to eq(
jsonrpc: '2.0',
id: 20,
result: [
newText: "puts 'bye'\n",
range: {
start: { line: 0, character: 0 }, end: { line: 1, character: 0 }
}
]
)
end
end
describe 'format with `safeAutocorrect: false`' do
let(:requests) do
[
{
jsonrpc: '2.0',
id: 2,
method: 'initialize',
params: {
probably: "Don't need real params for this test?",
initializationOptions: {
safeAutocorrect: false
}
}
},
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: "puts 'hi'",
uri: 'file:///path/to/file.rb',
version: 0
}
}
}, {
jsonrpc: '2.0',
method: 'textDocument/didChange',
params: {
contentChanges: [{ text: "puts 'bye'" }],
textDocument: {
uri: 'file:///path/to/file.rb',
version: 10
}
}
}, {
jsonrpc: '2.0',
id: 20,
method: 'textDocument/formatting',
params: {
options: { insertSpaces: true, tabSize: 2 },
textDocument: { uri: 'file:///path/to/file.rb' }
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
format_result = messages.last
expect(format_result).to eq(
jsonrpc: '2.0',
id: 20,
result: [
newText: "# frozen_string_literal: true\n\nputs 'bye'\n",
range: {
start: { line: 0, character: 0 }, end: { line: 1, character: 0 }
}
]
)
end
end
describe 'format without `lintMode` option' do
let(:requests) do
[
{
jsonrpc: '2.0',
id: 2,
method: 'initialize',
params: {
probably: "Don't need real params for this test?"
}
},
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: <<~RUBY,
puts foo.object_id == bar.object_id
puts 'hi'
RUBY
uri: 'file:///path/to/file.rb',
version: 0
}
}
}, {
jsonrpc: '2.0',
method: 'textDocument/didChange',
params: {
contentChanges: [
{
text: <<~RUBY
puts foo.object_id == bar.object_id
puts "hi"
RUBY
}
],
textDocument: {
uri: 'file:///path/to/file.rb',
version: 10
}
}
}, {
jsonrpc: '2.0',
id: 20,
method: 'textDocument/formatting',
params: {
options: { insertSpaces: true, tabSize: 2 },
textDocument: { uri: 'file:///path/to/file.rb' }
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
format_result = messages.last
expect(format_result).to eq(
jsonrpc: '2.0',
id: 20,
result: [
newText: <<~RUBY,
puts foo.equal?(bar)
puts 'hi'
RUBY
range: {
start: { line: 0, character: 0 }, end: { line: 3, character: 0 }
}
]
)
end
end
describe 'format with `lintMode: true`' do
let(:requests) do
[
{
jsonrpc: '2.0',
id: 2,
method: 'initialize',
params: {
probably: "Don't need real params for this test?",
initializationOptions: {
lintMode: true
}
}
},
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: <<~RUBY,
puts foo.object_id == bar.object_id
puts 'hi'
RUBY
uri: 'file:///path/to/file.rb',
version: 0
}
}
}, {
jsonrpc: '2.0',
method: 'textDocument/didChange',
params: {
contentChanges: [
{
text: <<~RUBY
puts foo.object_id == bar.object_id
puts "hi"
RUBY
}
],
textDocument: {
uri: 'file:///path/to/file.rb',
version: 10
}
}
}, {
jsonrpc: '2.0',
id: 20,
method: 'textDocument/formatting',
params: {
options: { insertSpaces: true, tabSize: 2 },
textDocument: { uri: 'file:///path/to/file.rb' }
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
format_result = messages.last
expect(format_result).to eq(
jsonrpc: '2.0',
id: 20,
result: [
newText: <<~RUBY,
puts foo.equal?(bar)
puts "hi"
RUBY
range: {
start: { line: 0, character: 0 }, end: { line: 3, character: 0 }
}
]
)
end
end
describe 'format with `lintMode: false`' do
let(:requests) do
[
{
jsonrpc: '2.0',
id: 2,
method: 'initialize',
params: {
probably: "Don't need real params for this test?",
initializationOptions: {
lintMode: false
}
}
},
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: <<~RUBY,
puts foo.object_id == bar.object_id
puts 'hi'
RUBY
uri: 'file:///path/to/file.rb',
version: 0
}
}
}, {
jsonrpc: '2.0',
method: 'textDocument/didChange',
params: {
contentChanges: [
{
text: <<~RUBY
puts foo.object_id == bar.object_id
puts "hi"
RUBY
}
],
textDocument: {
uri: 'file:///path/to/file.rb',
version: 10
}
}
}, {
jsonrpc: '2.0',
id: 20,
method: 'textDocument/formatting',
params: {
options: { insertSpaces: true, tabSize: 2 },
textDocument: { uri: 'file:///path/to/file.rb' }
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
format_result = messages.last
expect(format_result).to eq(
jsonrpc: '2.0',
id: 20,
result: [
newText: <<~RUBY,
puts foo.equal?(bar)
puts 'hi'
RUBY
range: {
start: { line: 0, character: 0 }, end: { line: 3, character: 0 }
}
]
)
end
end
describe 'format without `layoutMode` option' do
let(:requests) do
[
{
jsonrpc: '2.0',
id: 2,
method: 'initialize',
params: {
probably: "Don't need real params for this test?"
}
},
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: <<~RUBY,
puts "hi"
puts 'bye'
RUBY
uri: 'file:///path/to/file.rb',
version: 0
}
}
}, {
jsonrpc: '2.0',
method: 'textDocument/didChange',
params: {
contentChanges: [
{
text: <<~RUBY
puts "hi"
puts 'bye'
RUBY
}
],
textDocument: {
uri: 'file:///path/to/file.rb',
version: 10
}
}
}, {
jsonrpc: '2.0',
id: 20,
method: 'textDocument/formatting',
params: {
options: { insertSpaces: true, tabSize: 2 },
textDocument: { uri: 'file:///path/to/file.rb' }
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
format_result = messages.last
expect(format_result).to eq(
jsonrpc: '2.0',
id: 20,
result: [
newText: <<~RUBY,
puts 'hi'
puts 'bye'
RUBY
range: {
start: { line: 0, character: 0 }, end: { line: 3, character: 0 }
}
]
)
end
end
describe 'format with `layoutMode: true`' do
let(:requests) do
[
{
jsonrpc: '2.0',
id: 2,
method: 'initialize',
params: {
probably: "Don't need real params for this test?",
initializationOptions: {
layoutMode: true
}
}
},
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: <<~RUBY,
puts "hi"
puts 'bye'
RUBY
uri: 'file:///path/to/file.rb',
version: 0
}
}
}, {
jsonrpc: '2.0',
method: 'textDocument/didChange',
params: {
contentChanges: [
{
text: <<~RUBY
puts "hi"
puts 'bye'
RUBY
}
],
textDocument: {
uri: 'file:///path/to/file.rb',
version: 10
}
}
}, {
jsonrpc: '2.0',
id: 20,
method: 'textDocument/formatting',
params: {
options: { insertSpaces: true, tabSize: 2 },
textDocument: { uri: 'file:///path/to/file.rb' }
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
format_result = messages.last
expect(format_result).to eq(
jsonrpc: '2.0',
id: 20,
result: [
newText: <<~RUBY,
puts "hi"
puts 'bye'
RUBY
range: {
start: { line: 0, character: 0 }, end: { line: 3, character: 0 }
}
]
)
end
end
describe 'format with `layoutMode: false`' do
let(:requests) do
[
{
jsonrpc: '2.0',
id: 2,
method: 'initialize',
params: {
probably: "Don't need real params for this test?",
initializationOptions: {
layoutMode: false
}
}
},
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: <<~RUBY,
puts "hi"
puts 'bye'
RUBY
uri: 'file:///path/to/file.rb',
version: 0
}
}
}, {
jsonrpc: '2.0',
method: 'textDocument/didChange',
params: {
contentChanges: [
{
text: <<~RUBY
puts "hi"
puts 'bye'
RUBY
}
],
textDocument: {
uri: 'file:///path/to/file.rb',
version: 10
}
}
}, {
jsonrpc: '2.0',
id: 20,
method: 'textDocument/formatting',
params: {
options: { insertSpaces: true, tabSize: 2 },
textDocument: { uri: 'file:///path/to/file.rb' }
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
format_result = messages.last
expect(format_result).to eq(
jsonrpc: '2.0',
id: 20,
result: [
newText: <<~RUBY,
puts 'hi'
puts 'bye'
RUBY
range: {
start: { line: 0, character: 0 }, end: { line: 3, character: 0 }
}
]
)
end
end
describe 'format with `lintMode: true` and `layoutMode: true`' do
let(:requests) do
[
{
jsonrpc: '2.0',
id: 2,
method: 'initialize',
params: {
probably: "Don't need real params for this test?",
initializationOptions: {
lintMode: true,
layoutMode: true
}
}
},
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: <<~RUBY,
puts foo.object_id == bar.object_id
puts 'hi'
RUBY
uri: 'file:///path/to/file.rb',
version: 0
}
}
}, {
jsonrpc: '2.0',
method: 'textDocument/didChange',
params: {
contentChanges: [
{
text: <<~RUBY
puts foo.object_id == bar.object_id
puts "hi"
RUBY
}
],
textDocument: {
uri: 'file:///path/to/file.rb',
version: 10
}
}
}, {
jsonrpc: '2.0',
id: 20,
method: 'textDocument/formatting',
params: {
options: { insertSpaces: true, tabSize: 2 },
textDocument: { uri: 'file:///path/to/file.rb' }
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
format_result = messages.last
expect(format_result).to eq(
jsonrpc: '2.0',
id: 20,
result: [
newText: <<~RUBY,
puts foo.equal?(bar)
puts "hi"
RUBY
range: {
start: { line: 0, character: 0 }, end: { line: 3, character: 0 }
}
]
)
end
end
describe 'no op commands' do
let(:requests) do
[
{
jsonrpc: '2.0',
id: 1,
method: '$/cancelRequest',
params: {}
}, {
jsonrpc: '2.0',
id: 1,
method: '$/setTrace',
params: {}
}
]
end
it 'does not handle requests' do
expect(stderr).to eq('')
end
end
describe 'initialized' do
let(:requests) do
[
jsonrpc: '2.0', id: 1, method: 'initialized', params: {}
]
end
it 'logs the RuboCop version' do
expect(stderr).to match(/RuboCop \d+.\d+.\d+ language server initialized, PID \d+/)
end
end
describe 'format with unsynced file' do
let(:requests) do
[
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: "def hi\n [1, 2,\n 3 ]\nend\n",
uri: 'file:///path/to/file.rb',
version: 0
}
}
},
# didClose should cause the file to be unsynced
{
jsonrpc: '2.0',
method: 'textDocument/didClose',
params: {
textDocument: {
uri: 'file:///path/to/file.rb'
}
}
}, {
id: 20,
jsonrpc: '2.0',
method: 'textDocument/formatting',
params: {
options: { insertSpaces: true, tabSize: 2 },
textDocument: { uri: 'file:///path/to/file.rb' }
}
}
]
end
it 'handles requests' do
expect(stderr.chomp).to eq(
'[server] Format request arrived before text synchronized; ' \
"skipping: `file:///path/to/file.rb'"
)
format_result = messages.last
expect(format_result).to eq(jsonrpc: '2.0', id: 20, result: [])
end
end
describe 'unknown commands' do
let(:requests) do
[
id: 18,
jsonrpc: '2.0',
method: 'textDocument/didMassage',
params: {
textDocument: {
languageId: 'ruby',
text: "def hi\n [1, 2,\n 3 ]\nend\n",
uri: 'file:///path/to/file.rb',
version: 0
}
}
]
end
it 'handles requests' do
expect(stderr.chomp).to eq('[server] Unsupported Method: textDocument/didMassage')
expect(messages.last).to eq(
jsonrpc: '2.0',
id: 18,
error: {
code: LanguageServer::Protocol::Constant::ErrorCodes::METHOD_NOT_FOUND,
message: 'Unsupported Method: textDocument/didMassage'
}
)
end
end
describe 'methodless requests are acked' do
let(:requests) do
[
jsonrpc: '2.0', id: 1, result: {}
]
end
it 'handles requests' do
expect(stderr).to eq('')
expect(messages.last).to eq(jsonrpc: '2.0', id: 1, result: nil)
end
end
describe 'methodless and idless requests are dropped' do
let(:requests) do
[
jsonrpc: '2.0', result: {}
]
end
it 'handles requests' do
expect(stderr).to eq('')
expect(messages).to be_empty
end
end
describe 'execute command safe formatting' do
let(:requests) do
[
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: "puts 'hi'",
uri: 'file:///path/to/file.rb',
version: 0
}
}
}, {
jsonrpc: '2.0',
id: 99,
method: 'workspace/executeCommand',
params: {
command: 'rubocop.formatAutocorrects',
arguments: [uri: 'file:///path/to/file.rb']
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
expect(messages.last).to eq(
jsonrpc: '2.0',
id: 99,
method: 'workspace/applyEdit',
params: {
label: 'Format with RuboCop autocorrects',
edit: {
changes: {
'file:///path/to/file.rb': [
newText: "puts 'hi'\n",
range: {
start: { line: 0, character: 0 }, end: { line: 1, character: 0 }
}
]
}
}
}
)
end
end
describe 'execute command safe formatting with `Lint/UnusedBlockArgument` cop (`AutoCorrect: contextual`)' do
let(:requests) do
[
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
params: {
textDocument: {
languageId: 'ruby',
text: 'foo { |unused_variable| 42 }',
uri: 'file:///path/to/file.rb',
version: 0
}
}
}, {
jsonrpc: '2.0',
id: 99,
method: 'workspace/executeCommand',
params: {
command: 'rubocop.formatAutocorrects',
arguments: [uri: 'file:///path/to/file.rb']
}
}
]
end
it 'handles requests' do
expect(stderr).to eq('')
expect(messages.last).to eq(
jsonrpc: '2.0',
id: 99,
method: 'workspace/applyEdit',
params: {
label: 'Format with RuboCop autocorrects',
edit: {
changes: {
'file:///path/to/file.rb': [
newText: "foo { |_unused_variable| 42 }\n",
range: {
start: { line: 0, character: 0 }, end: { line: 1, character: 0 }
}
]
}
}
}
)
end
end
describe 'execute command unsafe formatting' do
let(:requests) do
[
{
jsonrpc: '2.0',
method: 'textDocument/didOpen',
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/lsp/severity_spec.rb | spec/rubocop/lsp/severity_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::LSP::Severity do
describe '.find_by' do
subject(:lsp_severity) { described_class.find_by(rubocop_severity) }
context 'when RuboCop severity is fatal' do
let(:rubocop_severity) { 'fatal' }
it { is_expected.to eq(LanguageServer::Protocol::Constant::DiagnosticSeverity::ERROR) }
end
context 'when RuboCop severity is error' do
let(:rubocop_severity) { 'error' }
it { is_expected.to eq(LanguageServer::Protocol::Constant::DiagnosticSeverity::ERROR) }
end
context 'when RuboCop severity is warning' do
let(:rubocop_severity) { 'warning' }
it { is_expected.to eq(LanguageServer::Protocol::Constant::DiagnosticSeverity::WARNING) }
end
context 'when RuboCop severity is convention' do
let(:rubocop_severity) { 'convention' }
it { is_expected.to eq(LanguageServer::Protocol::Constant::DiagnosticSeverity::INFORMATION) }
end
context 'when RuboCop severity is refactor' do
let(:rubocop_severity) { 'refactor' }
it { is_expected.to eq(LanguageServer::Protocol::Constant::DiagnosticSeverity::HINT) }
end
context 'when RuboCop severity is unknown severity' do
let(:rubocop_severity) { 'UNKNOWN' }
it { is_expected.to eq(LanguageServer::Protocol::Constant::DiagnosticSeverity::HINT) }
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/auto_gen_config_formatter_spec.rb | spec/rubocop/formatter/auto_gen_config_formatter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::AutoGenConfigFormatter do
subject(:formatter) { described_class.new(output) }
let(:output) { StringIO.new }
let(:files) do
%w[lib/rubocop.rb spec/spec_helper.rb exe/rubocop].map do |path|
File.expand_path(path)
end
end
describe '#report_file_as_mark' do
before { formatter.report_file_as_mark(offenses) }
def offense_with_severity(severity)
source_buffer = Parser::Source::Buffer.new('test', 1)
source_buffer.source = "a\n"
RuboCop::Cop::Offense.new(severity,
Parser::Source::Range.new(source_buffer, 0, 1),
'message',
'CopName')
end
context 'when no offenses are detected' do
let(:offenses) { [] }
it 'prints "."' do
expect(output.string).to eq('.')
end
end
context 'when a refactor severity offense is detected' do
let(:offenses) { [offense_with_severity(:refactor)] }
it 'prints "R"' do
expect(output.string).to eq('R')
end
end
context 'when a refactor convention offense is detected' do
let(:offenses) { [offense_with_severity(:convention)] }
it 'prints "C"' do
expect(output.string).to eq('C')
end
end
context 'when different severity offenses are detected' do
let(:offenses) { [offense_with_severity(:refactor), offense_with_severity(:error)] }
it 'prints highest level mark' do
expect(output.string).to eq('E')
end
end
end
describe '#finished' do
before { formatter.started(files) }
context 'when any offenses are detected' do
before do
source_buffer = Parser::Source::Buffer.new('test', 1)
source = Array.new(9) { |index| "This is line #{index + 1}." }
source_buffer.source = source.join("\n")
line_length = source[0].length + 1
formatter.file_started(files[0], {})
formatter.file_finished(
files[0],
[
RuboCop::Cop::Offense.new(
:convention,
Parser::Source::Range.new(source_buffer,
line_length + 2,
line_length + 3),
'foo',
'Cop'
)
]
)
end
it 'does not report offenses' do
formatter.finished(files)
expect(output.string).not_to include('Offenses:')
end
it 'outputs report summary' do
formatter.finished(files)
expect(output.string).to include(<<~OUTPUT)
3 files inspected, 1 offense detected, 1 offense autocorrectable
OUTPUT
end
end
context 'when no offenses are detected' do
before do
files.each do |file|
formatter.file_started(file, {})
formatter.file_finished(file, [])
end
end
it 'does not report offenses' do
formatter.finished(files)
expect(output.string).not_to include('Offenses:')
end
end
it 'calls #report_summary' do
formatter.finished(files)
expect(output.string).to include(<<~OUTPUT)
3 files inspected, no offenses detected
OUTPUT
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/fuubar_style_formatter_spec.rb | spec/rubocop/formatter/fuubar_style_formatter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::FuubarStyleFormatter do
subject(:formatter) { described_class.new(output) }
let(:output) { StringIO.new }
let(:files) { %w[lib/rubocop.rb spec/spec_helper.rb].map { |path| File.expand_path(path) } }
describe '#with_color' do
around do |example|
original_state = formatter.rainbow.enabled
begin
example.run
ensure
formatter.rainbow.enabled = original_state
end
end
context 'when color is enabled' do
before { formatter.rainbow.enabled = true }
it 'outputs coloring sequence code at the beginning and the end' do
formatter.with_color { formatter.output.write 'foo' }
expect(output.string).to eq("\e[32mfoo\e[0m")
end
end
context 'when color is disabled' do
before { formatter.rainbow.enabled = false }
it 'outputs nothing' do
formatter.with_color { formatter.output.write 'foo' }
expect(output.string).to eq('foo')
end
end
end
describe '#progressbar_color' do
before { formatter.started(files) }
def offense(severity, status = :uncorrected)
source_buffer = Parser::Source::Buffer.new('test', 1)
source = Array.new(9) { |index| "This is line #{index + 1}." }
source_buffer.source = source.join("\n")
line_length = source[0].length + 1
source_range = Parser::Source::Range.new(source_buffer, line_length + 2, line_length + 3)
RuboCop::Cop::Offense.new(severity, source_range, 'message', 'Cop', status)
end
context 'initially' do
it 'is green' do
expect(formatter.progressbar_color).to eq(:green)
end
end
context 'when no offenses are detected in a file' do
before { formatter.file_finished(files[0], []) }
it 'is still green' do
expect(formatter.progressbar_color).to eq(:green)
end
end
context 'when a convention offense is detected in a file' do
before { formatter.file_finished(files[0], [offense(:convention)]) }
it 'is yellow' do
expect(formatter.progressbar_color).to eq(:yellow)
end
end
context 'when an error offense is detected in a file' do
before { formatter.file_finished(files[0], [offense(:error)]) }
it 'is red' do
expect(formatter.progressbar_color).to eq(:red)
end
context 'and then a convention offense is detected in the next file' do
before { formatter.file_finished(files[1], [offense(:convention)]) }
it 'is still red' do
expect(formatter.progressbar_color).to eq(:red)
end
end
end
context 'when convention and error offenses are detected in a file' do
before do
offenses = [offense(:convention), offense(:error)]
formatter.file_finished(files[0], offenses)
end
it 'is red' do
expect(formatter.progressbar_color).to eq(:red)
end
end
context 'when an offense is detected in a file and autocorrected' do
before { formatter.file_finished(files[0], [offense(:convention, :corrected)]) }
it 'is green' do
expect(formatter.progressbar_color).to eq(:green)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/colorizable_spec.rb | spec/rubocop/formatter/colorizable_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::Colorizable do
let(:formatter_class) do
Class.new(RuboCop::Formatter::BaseFormatter) do
include RuboCop::Formatter::Colorizable
end
end
let(:options) { {} }
let(:formatter) { formatter_class.new(output, options) }
let(:output) { instance_double(IO) }
around do |example|
original_state = Rainbow.enabled
begin
example.run
ensure
Rainbow.enabled = original_state
end
end
describe '#colorize' do
subject(:colorized_output) { formatter.colorize('foo', :red) }
shared_examples 'does nothing' do
it 'does nothing' do
expect(colorized_output).to eq('foo')
end
end
context 'when the global Rainbow.enabled is true' do
before { Rainbow.enabled = true }
context "and the formatter's output is a tty" do
before { allow(output).to receive(:tty?).and_return(true) }
it 'colorizes the passed string' do
expect(colorized_output).to eq("\e[31mfoo\e[0m")
end
end
context "and the formatter's output is not a tty" do
before { allow(output).to receive(:tty?).and_return(false) }
it_behaves_like 'does nothing'
end
context 'and output is not a tty, but --color option was provided' do
let(:options) { { color: true } }
before { allow(output).to receive(:tty?).and_return(false) }
it 'colorizes the passed string' do
expect(colorized_output).to eq("\e[31mfoo\e[0m")
end
end
end
context 'when the global Rainbow.enabled is false' do
before { Rainbow.enabled = false }
context "and the formatter's output is a tty" do
before { allow(output).to receive(:tty?).and_return(true) }
it_behaves_like 'does nothing'
end
context "and the formatter's output is not a tty" do
before { allow(output).to receive(:tty?).and_return(false) }
it_behaves_like 'does nothing'
end
end
end
%i[
black
red
green
yellow
blue
magenta
cyan
white
].each do |color|
describe "##{color}" do
it "invokes #colorize(string, #{color}" do
expect(formatter).to receive(:colorize).with('foo', color)
formatter.public_send(color, 'foo')
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/emacs_style_formatter_spec.rb | spec/rubocop/formatter/emacs_style_formatter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::EmacsStyleFormatter, :config do
subject(:formatter) { described_class.new(output) }
let(:cop_class) { RuboCop::Cop::Base }
let(:source) { %w[a b cdefghi].join("\n") }
let(:output) { StringIO.new }
before { cop.send(:begin_investigation, processed_source) }
describe '#file_finished' do
it 'displays parsable text' do
cop.add_offense(Parser::Source::Range.new(source_buffer, 0, 1), message: 'message 1')
offenses = cop.add_offense(
Parser::Source::Range.new(source_buffer, 9, 10), message: 'message 2'
)
formatter.file_finished('test', offenses)
expect(output.string).to eq <<~OUTPUT
test:1:1: C: message 1
test:3:6: C: message 2
OUTPUT
end
context 'when the offense is automatically corrected' do
let(:file) { '/path/to/file' }
let(:offense) do
RuboCop::Cop::Offense.new(:convention, location, 'This is a message.', 'CopName', status)
end
let(:location) do
source_buffer = Parser::Source::Buffer.new('test', 1)
source_buffer.source = "a\n"
Parser::Source::Range.new(source_buffer, 0, 1)
end
let(:status) { :corrected }
it 'prints [Corrected] along with message' do
formatter.file_finished(file, [offense])
expect(output.string).to include(': [Corrected] This is a message.')
end
end
context 'when the offense is marked as todo' do
let(:file) { '/path/to/file' }
let(:offense) do
RuboCop::Cop::Offense.new(:convention, location, 'This is a message.', 'CopName', status)
end
let(:location) do
source_buffer = Parser::Source::Buffer.new('test', 1)
source_buffer.source = "a\n"
Parser::Source::Range.new(source_buffer, 0, 1)
end
let(:status) { :corrected_with_todo }
it 'prints [Todo] along with message' do
formatter.file_finished(file, [offense])
expect(output.string).to include(': [Todo] This is a message.')
end
end
context 'when the offense message contains a newline' do
let(:file) { '/path/to/file' }
let(:offense) do
RuboCop::Cop::Offense.new(:error, location,
"unmatched close parenthesis: /\n world " \
"# Some comment containing a )\n/",
'CopName', :uncorrected)
end
let(:location) do
source_buffer = Parser::Source::Buffer.new('test', 1)
source_buffer.source = "a\n"
Parser::Source::Range.new(source_buffer, 0, 1)
end
it 'strips newlines out of the error message' do
formatter.file_finished(file, [offense])
expect(output.string).to eq(
'/path/to/file:1:1: E: [Correctable] unmatched close parenthesis: / ' \
"world # Some comment containing a ) /\n"
)
end
end
end
describe '#finished' do
it 'does not report summary' do
formatter.finished(['/path/to/file'])
expect(output.string).to be_empty
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/html_formatter_spec.rb | spec/rubocop/formatter/html_formatter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::HTMLFormatter, :isolated_environment do
spec_root = File.expand_path('../..', __dir__)
around do |example|
project_path = File.join(spec_root, 'fixtures/html_formatter/project')
FileUtils.cp_r(project_path, '.')
Dir.chdir(File.basename(project_path)) { example.run }
end
let(:enabled_cops) do
[
'Layout/EmptyLinesAroundAccessModifier', 'Layout/IndentationConsistency',
'Layout/IndentationWidth', 'Layout/LineLength', 'Lint/UselessAssignment',
'Naming/MethodName', 'Style/Documentation', 'Style/EmptyMethod',
'Style/FrozenStringLiteralComment', 'Style/RedundantRegexpArgument', 'Style/RegexpLiteral',
'Style/RescueModifier', 'Style/SymbolArray'
].join(',')
end
let(:options) do
['--only', enabled_cops, '--format', 'html', '--out']
end
let(:actual_html_path) do
path = File.expand_path('result.html')
RuboCop::CLI.new.run([*options, path])
path
end
let(:actual_html_path_cached) do
path = File.expand_path('result_cached.html')
2.times { RuboCop::CLI.new.run([*options, path]) }
path
end
let(:actual_html) { File.read(actual_html_path, encoding: Encoding::UTF_8) }
let(:actual_html_cached) { File.read(actual_html_path_cached, encoding: Encoding::UTF_8) }
let(:expected_html_path) { File.join(spec_root, 'fixtures/html_formatter/expected.html') }
let(:expected_html) do
html = File.read(expected_html_path, encoding: Encoding::UTF_8)
# Avoid failure on version bump
html.sub(/(class="version".{0,20})\d+(?:\.\d+){2}/i) do
Regexp.last_match(1) + RuboCop::Version::STRING
end
end
it 'outputs the result in HTML' do
# FileUtils.copy(actual_html_path, expected_html_path)
expect(actual_html).to eq(expected_html)
end
it 'outputs the cached result in HTML' do
# FileUtils.copy(actual_html_path, expected_html_path)
expect(actual_html_cached).to eq(expected_html)
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/simple_text_formatter_spec.rb | spec/rubocop/formatter/simple_text_formatter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::SimpleTextFormatter do
subject(:formatter) { described_class.new(output) }
before { Rainbow.enabled = true }
after { Rainbow.enabled = false }
let(:output) { StringIO.new }
shared_examples 'report for severity' do |severity|
let(:offense) do
RuboCop::Cop::Offense.new(severity, location,
'This is a message with `colored text`.',
'CopName', status)
end
context 'the file is under the current working directory' do
let(:file) { File.expand_path('spec/spec_helper.rb') }
it 'prints as relative path' do
expect(output.string).to include('== spec/spec_helper.rb ==')
end
end
context 'the file is outside of the current working directory' do
let(:file) do
tempfile = Tempfile.new('')
tempfile.close
File.expand_path(tempfile.path)
end
it 'prints as absolute path' do
expect(output.string).to include("== #{file} ==")
end
end
context 'when the offense is not corrected' do
let(:status) { :unsupported }
it 'prints message as-is' do
expect(output.string).to include(': This is a message with colored text.')
end
end
context 'when the offense is correctable' do
let(:status) { :uncorrected }
it 'prints message as-is' do
expect(output.string).to include(': [Correctable] This is a message with colored text.')
end
end
context 'when the offense is automatically corrected' do
let(:status) { :corrected }
it 'prints [Corrected] along with message' do
expect(output.string).to include(': [Corrected] This is a message with colored text.')
end
end
context 'when the offense is marked as todo' do
let(:status) { :corrected_with_todo }
it 'prints [Todo] along with message' do
expect(output.string).to include(': [Todo] This is a message with colored text.')
end
end
end
describe '#report_file' do
before { formatter.report_file(file, [offense]) }
let(:file) { '/path/to/file' }
let(:location) do
source_buffer = Parser::Source::Buffer.new('test', 1)
source_buffer.source = "a\n"
Parser::Source::Range.new(source_buffer, 0, 1)
end
let(:status) { :uncorrected }
it_behaves_like 'report for severity', :info
it_behaves_like 'report for severity', :refactor
it_behaves_like 'report for severity', :convention
it_behaves_like 'report for severity', :warning
it_behaves_like 'report for severity', :error
it_behaves_like 'report for severity', :fatal
end
describe '#report_summary' do
context 'when no files inspected' do
it 'handles pluralization correctly' do
formatter.report_summary(0, 0, 0, 0)
expect(output.string).to eq(<<~OUTPUT)
0 files inspected, no offenses detected
OUTPUT
end
end
context 'when a file inspected and no offenses detected' do
it 'handles pluralization correctly' do
formatter.report_summary(1, 0, 0, 0)
expect(output.string).to eq(<<~OUTPUT)
1 file inspected, no offenses detected
OUTPUT
end
end
context 'when an offense detected' do
it 'handles pluralization correctly' do
formatter.report_summary(1, 1, 0, 0)
expect(output.string).to eq(<<~OUTPUT)
1 file inspected, 1 offense detected
OUTPUT
end
end
context 'when an offense detected and an offense autocorrectable' do
it 'handles pluralization correctly' do
formatter.report_summary(1, 1, 0, 1)
expect(output.string).to eq(<<~OUTPUT)
1 file inspected, 1 offense detected, 1 offense autocorrectable
OUTPUT
end
end
context 'when 2 offenses detected' do
it 'handles pluralization correctly' do
formatter.report_summary(2, 2, 0, 0)
expect(output.string).to eq(<<~OUTPUT)
2 files inspected, 2 offenses detected
OUTPUT
end
end
context 'when 2 offenses detected and 2 offenses autocorrectable' do
it 'handles pluralization correctly' do
formatter.report_summary(2, 2, 0, 2)
expect(output.string).to eq(<<~OUTPUT)
2 files inspected, 2 offenses detected, 2 offenses autocorrectable
OUTPUT
end
end
context 'when an offense is corrected' do
it 'prints about correction' do
formatter.report_summary(1, 1, 1, 0)
expect(output.string).to eq(<<~OUTPUT)
1 file inspected, 1 offense detected, 1 offense corrected
OUTPUT
end
end
context 'when 2 offenses are corrected' do
it 'handles pluralization correctly' do
formatter.report_summary(1, 1, 2, 0)
expect(output.string).to eq(<<~OUTPUT)
1 file inspected, 1 offense detected, 2 offenses corrected
OUTPUT
end
end
context 'when 2 offenses are corrected and 2 offenses autocorrectable' do
it 'handles pluralization correctly' do
formatter.report_summary(1, 1, 2, 2)
expect(output.string).to eq(<<~OUTPUT)
1 file inspected, 1 offense detected, 2 offenses corrected, 2 offenses autocorrectable
OUTPUT
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/text_util_spec.rb | spec/rubocop/formatter/text_util_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::TextUtil do
describe 'pluralize' do
it 'does not change 0 to no' do
pluralized_text = described_class.pluralize(0, 'file')
expect(pluralized_text).to eq('0 files')
end
it 'changes 0 to no when configured' do
pluralized_text = described_class.pluralize(0, 'file', no_for_zero: true)
expect(pluralized_text).to eq('no files')
end
it 'does not pluralize 1' do
pluralized_text = described_class.pluralize(1, 'file')
expect(pluralized_text).to eq('1 file')
end
it 'pluralizes quantities greater than 1' do
pluralized_text = described_class.pluralize(3, 'file')
expect(pluralized_text).to eq('3 files')
end
it 'pluralizes fractions' do
pluralized_text = described_class.pluralize(0.5, 'file')
expect(pluralized_text).to eq('0.5 files')
end
it 'pluralizes -1' do
pluralized_text = described_class.pluralize(-1, 'file')
expect(pluralized_text).to eq('-1 files')
end
it 'pluralizes negative quantities less than -1' do
pluralized_text = described_class.pluralize(-2, 'file')
expect(pluralized_text).to eq('-2 files')
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/disabled_config_formatter_spec.rb | spec/rubocop/formatter/disabled_config_formatter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::DisabledConfigFormatter, :isolated_environment,
:restore_registry do
include FileHelper
subject(:formatter) { described_class.new(output) }
include_context 'mock console output'
let(:output) do
io = StringIO.new
def io.path
'.rubocop_todo.yml'
end
io
end
let(:offenses) do
[RuboCop::Cop::Offense.new(:convention, location, 'message', 'Test/Cop1'),
RuboCop::Cop::Offense.new(:convention, location, 'message', 'Test/Cop2')]
end
let(:location) { FakeLocation.new(line: 1, column: 5) }
let(:heading) do
format(
described_class::HEADING,
command: expected_heading_command,
timestamp: expected_heading_timestamp
)
end
let(:expected_heading_command) { 'rubocop --auto-gen-config' }
let(:expected_heading_timestamp) { "on #{Time.now} " }
let(:config_store) { instance_double(RuboCop::ConfigStore) }
let(:options) { { config_store: config_store } }
before do
stub_cop_class('Test::Cop1')
stub_cop_class('Test::Cop2')
# Avoid intermittent failure when another test set ConfigLoader options
RuboCop::ConfigLoader.clear_options
allow(Time).to receive(:now).and_return(Time.now)
allow(config_store).to receive(:for_pwd).and_return(instance_double(RuboCop::Config))
end
context 'when any offenses are detected' do
before do
formatter.started(['test_a.rb', 'test_b.rb'])
formatter.file_started('test_a.rb', options)
formatter.file_finished('test_a.rb', offenses)
formatter.file_started('test_b.rb', options)
formatter.file_finished('test_b.rb', [offenses.first])
formatter.finished(['test_a.rb', 'test_b.rb'])
end
let(:expected_rubocop_todo) do
[heading,
'# Offense count: 2',
'Test/Cop1:',
' Exclude:',
" - 'test_a.rb'",
" - 'test_b.rb'",
'',
'# Offense count: 1',
'Test/Cop2:',
' Exclude:',
" - 'test_a.rb'",
''].join("\n")
end
it 'displays YAML configuration disabling all cops with offenses' do
expect(output.string).to eq(expected_rubocop_todo)
expect($stdout.string).to eq("Created .rubocop_todo.yml.\n")
end
end
context "when there's .rubocop.yml" do
before do
create_file('.rubocop.yml', <<~'YAML')
Test/Cop1:
Exclude:
- Gemfile
Test/Cop2:
Exclude:
- "**/*.blah"
- !ruby/regexp /.*/bar/*/foo\.rb$/
YAML
formatter.started(['test_a.rb', 'test_b.rb'])
formatter.file_started('test_a.rb', options)
formatter.file_finished('test_a.rb', offenses)
formatter.file_started('test_b.rb', options)
formatter.file_finished('test_b.rb', [offenses.first])
allow(RuboCop::ConfigLoader.default_configuration).to receive(:[]).and_return({})
formatter.finished(['test_a.rb', 'test_b.rb'])
end
let(:expected_rubocop_todo) do
[heading,
'# Offense count: 2',
'Test/Cop1:',
' Exclude:',
" - 'Gemfile'",
" - 'test_a.rb'",
" - 'test_b.rb'",
'',
'# Offense count: 1',
'Test/Cop2:',
' Exclude:',
" - '**/*.blah'",
' - !ruby/regexp /.*/bar/*/foo\.rb$/',
" - 'test_a.rb'",
''].join("\n")
end
it 'merges in excludes from .rubocop.yml' do
expect(output.string).to eq(expected_rubocop_todo)
end
end
context 'when exclude_limit option is omitted' do
before do
formatter.started(filenames)
filenames.each do |filename|
formatter.file_started(filename, options)
if filename == filenames.last
formatter.file_finished(filename, [offenses.first])
else
formatter.file_finished(filename, offenses)
end
end
formatter.finished(filenames)
end
let(:filenames) { Array.new(16) { |index| format('test_%02d.rb', index + 1) } }
let(:expected_rubocop_todo) do
[heading,
'# Offense count: 16',
'Test/Cop1:',
' Enabled: false',
'',
'# Offense count: 15',
'Test/Cop2:',
' Exclude:',
" - 'test_01.rb'",
" - 'test_02.rb'",
" - 'test_03.rb'",
" - 'test_04.rb'",
" - 'test_05.rb'",
" - 'test_06.rb'",
" - 'test_07.rb'",
" - 'test_08.rb'",
" - 'test_09.rb'",
" - 'test_10.rb'",
" - 'test_11.rb'",
" - 'test_12.rb'",
" - 'test_13.rb'",
" - 'test_14.rb'",
" - 'test_15.rb'",
''].join("\n")
end
it 'disables the cop with 15 offending files' do
expect(output.string).to eq(expected_rubocop_todo)
end
end
context 'when exclude_limit option is passed' do
before do
formatter.started(filenames)
filenames.each do |filename|
formatter.file_started(filename, options)
if filename == filenames.last
formatter.file_finished(filename, [offenses.first])
else
formatter.file_finished(filename, offenses)
end
end
formatter.finished(filenames)
end
let(:formatter) { described_class.new(output, exclude_limit: 5) }
let(:filenames) { Array.new(6) { |index| format('test_%02d.rb', index + 1) } }
let(:expected_heading_command) { 'rubocop --auto-gen-config --exclude-limit 5' }
let(:expected_rubocop_todo) do
[heading,
'# Offense count: 6',
'Test/Cop1:',
' Enabled: false',
'',
'# Offense count: 5',
'Test/Cop2:',
' Exclude:',
" - 'test_01.rb'",
" - 'test_02.rb'",
" - 'test_03.rb'",
" - 'test_04.rb'",
" - 'test_05.rb'",
''].join("\n")
end
it 'respects the file exclusion list limit' do
expect(output.string).to eq(expected_rubocop_todo)
end
end
context 'when no files are inspected' do
before do
formatter.started([])
formatter.finished([])
end
it 'creates a .rubocop_todo.yml even in such case' do
expect(output.string).to eq(heading)
end
end
context 'with autocorrect supported cop', :restore_registry do
before do
stub_cop_class('Test::Cop3') { extend RuboCop::Cop::AutoCorrector }
formatter.started(['test_autocorrect.rb'])
formatter.file_started('test_autocorrect.rb', options)
formatter.file_finished('test_autocorrect.rb', offenses)
formatter.finished(['test_autocorrect.rb'])
end
let(:expected_rubocop_todo) do
[heading,
'# Offense count: 1',
'# This cop supports safe autocorrection (--autocorrect).',
'Test/Cop3:',
' Exclude:',
" - 'test_autocorrect.rb'",
''].join("\n")
end
let(:offenses) do
[
RuboCop::Cop::Offense.new(:convention, location, 'message', 'Test/Cop3')
]
end
it 'adds a comment about --autocorrect option' do
expect(output.string).to eq(expected_rubocop_todo)
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/quiet_formatter_spec.rb | spec/rubocop/formatter/quiet_formatter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::QuietFormatter do
subject(:formatter) { described_class.new(output) }
before { Rainbow.enabled = true }
after { Rainbow.enabled = false }
let(:output) { StringIO.new }
describe '#report_file' do
before { formatter.report_file(file, [offense]) }
let(:file) { '/path/to/file' }
let(:offense) do
RuboCop::Cop::Offense.new(:convention, location,
'This is a message with `colored text`.',
'CopName', status)
end
let(:location) do
source_buffer = Parser::Source::Buffer.new('test', 1)
source_buffer.source = "a\n"
Parser::Source::Range.new(source_buffer, 0, 1)
end
let(:status) { :uncorrected }
context 'the file is under the current working directory' do
let(:file) { File.expand_path('spec/spec_helper.rb') }
it 'prints as relative path' do
expect(output.string).to include('== spec/spec_helper.rb ==')
end
end
context 'the file is outside of the current working directory' do
let(:file) do
tempfile = Tempfile.new('')
tempfile.close
File.expand_path(tempfile.path)
end
it 'prints as absolute path' do
expect(output.string).to include("== #{file} ==")
end
end
context 'when the offense is not corrected' do
let(:status) { :unsupported }
it 'prints message as-is' do
expect(output.string).to include(': This is a message with colored text.')
end
end
context 'when the offense is correctable' do
let(:status) { :uncorrected }
it 'prints message as-is' do
expect(output.string).to include(': [Correctable] This is a message with colored text.')
end
end
context 'when the offense is automatically corrected' do
let(:status) { :corrected }
it 'prints [Corrected] along with message' do
expect(output.string).to include(': [Corrected] This is a message with colored text.')
end
end
end
describe '#report_summary' do
context 'when no files inspected' do
it 'handles pluralization correctly' do
formatter.report_summary(0, 0, 0, 0)
expect(output.string).to be_empty
end
end
context 'when a file inspected and no offenses detected' do
it 'handles pluralization correctly' do
formatter.report_summary(1, 0, 0, 0)
expect(output.string).to be_empty
end
end
context 'when an offense detected' do
it 'handles pluralization correctly' do
formatter.report_summary(1, 1, 0, 0)
expect(output.string).to eq(<<~OUTPUT)
1 file inspected, 1 offense detected
OUTPUT
end
end
context 'when an offense detected and an offense correctable' do
it 'handles pluralization correctly' do
formatter.report_summary(1, 1, 0, 1)
expect(output.string).to eq(<<~OUTPUT)
1 file inspected, 1 offense detected, 1 offense autocorrectable
OUTPUT
end
end
context 'when 2 offenses detected' do
it 'handles pluralization correctly' do
formatter.report_summary(2, 2, 0, 0)
expect(output.string).to eq(<<~OUTPUT)
2 files inspected, 2 offenses detected
OUTPUT
end
end
context 'when 2 offenses detected and 2 offenses correctable' do
it 'handles pluralization correctly' do
formatter.report_summary(2, 2, 0, 2)
expect(output.string).to eq(<<~OUTPUT)
2 files inspected, 2 offenses detected, 2 offenses autocorrectable
OUTPUT
end
end
context 'when an offense is corrected' do
it 'prints about correction' do
formatter.report_summary(1, 1, 1, 0)
expect(output.string).to eq(<<~OUTPUT)
1 file inspected, 1 offense detected, 1 offense corrected
OUTPUT
end
end
context 'when 2 offenses are corrected' do
it 'handles pluralization correctly' do
formatter.report_summary(1, 1, 2, 0)
expect(output.string).to eq(<<~OUTPUT)
1 file inspected, 1 offense detected, 2 offenses corrected
OUTPUT
end
end
context 'when 2 offenses are corrected and 2 offenses correctable' do
it 'handles pluralization correctly' do
formatter.report_summary(1, 1, 2, 2)
expect(output.string).to eq(<<~OUTPUT)
1 file inspected, 1 offense detected, 2 offenses corrected, 2 offenses autocorrectable
OUTPUT
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/file_list_formatter_spec.rb | spec/rubocop/formatter/file_list_formatter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::FileListFormatter, :config do
subject(:formatter) { described_class.new(output) }
let(:output) { StringIO.new }
let(:cop_class) { RuboCop::Cop::Base }
let(:source) { %w[a b cdefghi].join("\n") }
before { cop.send(:begin_investigation, processed_source) }
describe '#file_finished' do
it 'displays parsable text' do
cop.add_offense(Parser::Source::Range.new(source_buffer, 0, 1), message: 'message 1')
offenses = cop.add_offense(
Parser::Source::Range.new(source_buffer, 9, 10), message: 'message 2'
)
formatter.file_finished('test', offenses)
formatter.file_finished('test_2', offenses)
expect(output.string).to eq "test\ntest_2\n"
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/worst_offenders_formatter_spec.rb | spec/rubocop/formatter/worst_offenders_formatter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::WorstOffendersFormatter do
subject(:formatter) { described_class.new(output) }
let(:output) { StringIO.new }
let(:files) do
%w[lib/rubocop.rb spec/spec_helper.rb exe/rubocop].map do |path|
File.expand_path(path)
end
end
describe '#finished' do
context 'when there are many offenses' do
let(:offense) { instance_double(RuboCop::Cop::Offense) }
before do
formatter.started(files)
files.each_with_index do |file, index|
formatter.file_finished(file, [offense] * (index + 2))
end
end
it 'sorts by offense count first and then by cop name' do
formatter.finished(files)
expect(output.string).to eq(<<~OUTPUT)
4 exe/rubocop
3 spec/spec_helper.rb
2 lib/rubocop.rb
--
9 Total in 3 files
OUTPUT
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/json_formatter_spec.rb | spec/rubocop/formatter/json_formatter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::JSONFormatter do
subject(:formatter) { described_class.new(output) }
let(:output) { StringIO.new }
let(:files) { %w[/path/to/file1 /path/to/file2] }
let(:location) do
source_buffer = Parser::Source::Buffer.new('test', 1)
source_buffer.source = %w[a b cdefghi].join("\n")
Parser::Source::Range.new(source_buffer, 2, 10)
end
let(:offense) do
RuboCop::Cop::Offense.new(:convention, location, 'This is message', 'CopName', :corrected)
end
describe '#started' do
let(:summary) { formatter.output_hash[:summary] }
it 'sets target file count in summary' do
expect(summary[:target_file_count]).to be_nil
formatter.started(%w[/path/to/file1 /path/to/file2])
expect(summary[:target_file_count]).to eq(2)
end
end
describe '#file_finished' do
before do
count = 0
allow(formatter).to receive(:hash_for_file) do
count += 1
end
end
let(:summary) { formatter.output_hash[:summary] }
it 'adds detected offense count in summary' do
expect(summary[:offense_count]).to eq(0)
formatter.file_started(files[0], {})
expect(summary[:offense_count]).to eq(0)
formatter.file_finished(files[0], [
instance_double(RuboCop::Cop::Offense),
instance_double(RuboCop::Cop::Offense)
])
expect(summary[:offense_count]).to eq(2)
end
it 'adds value of #hash_for_file to #output_hash[:files]' do
expect(formatter.output_hash[:files]).to be_empty
formatter.file_started(files[0], {})
expect(formatter.output_hash[:files]).to be_empty
formatter.file_finished(files[0], [])
expect(formatter.output_hash[:files]).to eq([1])
formatter.file_started(files[1], {})
expect(formatter.output_hash[:files]).to eq([1])
formatter.file_finished(files[1], [])
expect(formatter.output_hash[:files]).to eq([1, 2])
end
end
describe '#finished' do
let(:summary) { formatter.output_hash[:summary] }
it 'sets inspected file count in summary' do
expect(summary[:inspected_file_count]).to be_nil
formatter.finished(%w[/path/to/file1 /path/to/file2])
expect(summary[:inspected_file_count]).to eq(2)
end
it 'outputs #output_hash as JSON' do
formatter.finished(files)
json = output.string
restored_hash = JSON.parse(json, symbolize_names: true)
expect(restored_hash).to eq(formatter.output_hash)
end
end
describe '#hash_for_file' do
subject(:hash) { formatter.hash_for_file(file, offenses) }
let(:file) { File.expand_path('spec/spec_helper.rb') }
let(:offenses) do
[
instance_double(RuboCop::Cop::Offense),
instance_double(RuboCop::Cop::Offense)
]
end
before do
count = 0
allow(formatter).to receive(:hash_for_offense) do
count += 1
end
end
it 'sets relative file path for :path key' do
expect(hash[:path]).to eq('spec/spec_helper.rb')
end
it 'sets an array of #hash_for_offense values for :offenses key' do
expect(hash[:offenses]).to eq([1, 2])
end
end
describe '#hash_for_offense' do
subject(:hash) { formatter.hash_for_offense(offense) }
it 'sets Offense#severity value for :severity key' do
expect(hash[:severity]).to eq(:convention)
end
it 'sets Offense#message value for :message key' do
expect(hash[:message]).to eq('This is message')
end
it 'sets Offense#cop_name value for :cop_name key' do
expect(hash[:cop_name]).to eq('CopName')
end
it 'sets Offense#correctable? value for :correctable key' do
expect(hash[:correctable]).to be(true)
end
it 'sets Offense#corrected? value for :corrected key' do
expect(hash[:corrected]).to be(true)
end
it 'sets value of #hash_for_location for :location key' do
location_hash = {
start_line: 2,
start_column: 1,
last_line: 3,
last_column: 6,
length: 8,
line: 2,
column: 1
}
expect(hash[:location]).to eq(location_hash)
end
end
describe '#hash_for_location' do
subject(:hash) { formatter.hash_for_location(offense) }
it 'sets line value for :line key' do
expect(hash[:line]).to eq(2)
end
it 'sets column value for :column key' do
expect(hash[:column]).to eq(1)
end
it 'sets length value for :length key' do
expect(hash[:length]).to eq(8)
end
context 'when the location is pseudo' do
let(:location) { RuboCop::Cop::Offense::NO_LOCATION }
it 'returns a valid hash' do
expect(hash).to eq({
start_line: 1,
start_column: 1,
last_line: 1,
last_column: 1,
length: 0,
line: 1,
column: 1
})
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/tap_formatter_spec.rb | spec/rubocop/formatter/tap_formatter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::TapFormatter do
subject(:formatter) { described_class.new(output) }
let(:output) { StringIO.new }
let(:files) do
%w[lib/rubocop.rb spec/spec_helper.rb exe/rubocop].map do |path|
File.expand_path(path)
end
end
describe '#file_finished' do
before do
formatter.started(files)
formatter.file_started(files.first, {})
formatter.file_finished(files.first, offenses)
end
context 'when no offenses are detected' do
let(:offenses) { [] }
it 'prints "ok"' do
expect(output.string).to include('ok 1')
end
end
context 'when any offenses are detected' do
let(:offenses) do
source_buffer = Parser::Source::Buffer.new('test', 1)
source = Array.new(9) { |index| "This is line #{index + 1}." }
source_buffer.source = source.join("\n")
line_length = source[0].length + 1
[
RuboCop::Cop::Offense.new(
:convention,
Parser::Source::Range.new(source_buffer,
line_length + 2,
line_length + 3),
'foo',
'Cop'
)
]
end
it 'prints "not ok"' do
expect(output.string).to include('not ok 1')
end
end
end
describe '#finished' do
before { formatter.started(files) }
context 'when any offenses are detected' do
before do
source_buffer = Parser::Source::Buffer.new('test', 1)
source = Array.new(9) { |index| "This is line #{index + 1}." }
source_buffer.source = source.join("\n")
line_length = source[0].length + 1
formatter.file_started(files[0], {})
formatter.file_finished(
files[0],
[
RuboCop::Cop::Offense.new(
:convention,
Parser::Source::Range.new(source_buffer,
line_length + 2,
line_length + 3),
'foo',
'Cop'
)
]
)
formatter.file_started(files[1], {})
formatter.file_finished(files[1], [])
formatter.file_started(files[2], {})
formatter.file_finished(
files[2],
[
RuboCop::Cop::Offense.new(
:error,
Parser::Source::Range.new(source_buffer,
(line_length * 4) + 1,
(line_length * 4) + 2),
'bar',
'Cop'
),
RuboCop::Cop::Offense.new(
:convention,
Parser::Source::Range.new(source_buffer,
line_length * 5,
(line_length * 5) + 1),
'foo',
'Cop'
)
]
)
end
it 'reports all detected offenses for all failed files' do
formatter.finished(files)
expect(output.string).to include(<<~OUTPUT)
1..3
not ok 1 - lib/rubocop.rb
# lib/rubocop.rb:2:3: C: [Correctable] foo
# This is line 2.
# ^
ok 2 - spec/spec_helper.rb
not ok 3 - exe/rubocop
# exe/rubocop:5:2: E: [Correctable] bar
# This is line 5.
# ^
# exe/rubocop:6:1: C: [Correctable] foo
# This is line 6.
# ^
OUTPUT
end
end
context 'when no offenses are detected' do
before do
files.each do |file|
formatter.file_started(file, {})
formatter.file_finished(file, [])
end
end
it 'does not report offenses' do
formatter.finished(files)
expect(output.string).not_to include('not ok')
end
end
end
describe '#report_file', :config do
let(:cop_class) { RuboCop::Cop::Base }
let(:output) { StringIO.new }
before { cop.send(:begin_investigation, processed_source) }
context 'when the source contains multibyte characters' do
let(:source) do
<<~RUBY
do_something("γγγ", ["γγγ"])
RUBY
end
it 'displays text containing the offending source line' do
range = source_range(source.index('[')..source.index(']'))
offenses = cop.add_offense(range, message: 'message 1')
formatter.report_file('test', offenses)
expect(output.string)
.to eq <<~OUTPUT
# test:1:21: C: message 1
# do_something("γγγ", ["γγγ"])
# ^^^^^^^^^^
OUTPUT
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/pacman_formatter_spec.rb | spec/rubocop/formatter/pacman_formatter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Formatter::PacmanFormatter do
subject(:formatter) { described_class.new(output) }
let(:output) { StringIO.new }
describe '#next_step' do
subject(:next_step) { formatter.next_step(offenses) }
context 'when no offenses are detected' do
let(:offenses) { [] }
it 'calls the step function with a dot' do
expect(formatter).to receive(:step).with('.')
next_step
end
end
context 'when an offense is detected in a file' do
let(:location) { FakeLocation.new(line: 1, column: 5) }
let(:expected_character) { Rainbow(described_class::GHOST).red }
let(:offenses) { [RuboCop::Cop::Offense.new(:error, location, 'message', 'CopA')] }
it 'calls the step function with a dot' do
expect(formatter).to receive(:step).with(expected_character)
next_step
end
end
end
describe '#update_progress_line' do
subject(:update_progress_line) { formatter.update_progress_line }
before do
formatter.instance_variable_set(:@total_files, files)
allow(formatter).to receive(:cols).and_return(cols)
end
context 'when total_files is greater than columns in the terminal' do
let(:files) { 10 }
let(:cols) { 2 }
it 'updates the progress_line properly' do
update_progress_line
expect(formatter.progress_line).to eq(described_class::PACDOT * cols)
end
context 'when need to change the line' do
let(:files) { 18 }
let(:cols) { 10 }
before { formatter.instance_variable_set(:@repetitions, 1) }
it 'updates the progress_line properly' do
update_progress_line
expect(formatter.progress_line).to eq(described_class::PACDOT * 8)
end
end
end
context 'when total_files less than columns in the terminal' do
let(:files) { 10 }
let(:cols) { 11 }
it 'updates the progress_line properly' do
update_progress_line
expect(formatter.progress_line).to eq(described_class::PACDOT * files)
end
end
end
describe '#step' do
subject(:step) { formatter.step(character) }
let(:initial_progress_line) { format('..%s', described_class::PACDOT * 2) }
before { formatter.instance_variable_set(:@progress_line, initial_progress_line) }
context 'character is Pacman' do
let(:character) { described_class::PACMAN }
let(:expected_progress_line) { format('..%s%s', character, described_class::PACDOT) }
it 'removes the first β’ and puts a α§' do
step
expect(formatter.progress_line).to eq(expected_progress_line)
end
end
context 'character is a Pacdot' do
let(:character) { described_class::PACDOT }
it 'leaves the progress_line as it is' do
expect { step }.not_to change(formatter, :progress_line)
end
end
context 'character is normal dot' do
let(:character) { '.' }
it 'removes the first β’ and puts a .' do
step
expect(formatter.progress_line).to eq("...#{described_class::PACDOT}")
end
end
context 'character is ghost' do
let(:character) { Rainbow(described_class::GHOST).red }
let(:expected_progress_line) { format('..%s%s', character, described_class::PACDOT) }
it 'removes the first β’ and puts ghosts' do
step
expect(formatter.progress_line).to eq(expected_progress_line)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.