Skip to content

Instantly share code, notes, and snippets.

@glaucocustodio
Last active July 10, 2024 14:02
Show Gist options
  • Save glaucocustodio/36e0fafb9137a482ec8cfdc794ca36a7 to your computer and use it in GitHub Desktop.
Save glaucocustodio/36e0fafb9137a482ec8cfdc794ca36a7 to your computer and use it in GitHub Desktop.
custom rubocop cop for checking if spec files include `require 'rails_helper'`
# frozen_string_literal: true
# put this file at .rubocop/cop/rspec/redundant_require_rails_helper.rb
# then ensure you have the following in .rubocop.yml:
#
# require:
# - .rubocop/cop/rspec/redundant_require_rails_helper.rb
#
# RSpec/RedundantRequireRailsHelper:
# Enabled: true
module RuboCop
module Cop
module RSpec
# Checks spec files for the presence of `require 'rails_helper'`.
#
# @example
# # bad
# require 'rails_helper'
#
# # good
# # No `require 'rails_helper'` at the top of the file
class RedundantRequireRailsHelper < Cop
MSG = "Do not require 'rails_helper' in spec files since it's already required by the .rspec file."
def on_new_investigation
file_path = processed_source.file_path
return unless spec_file?(file_path)
require_nodes = processed_source.ast.each_node(:send).select do |send_node|
require_rails_helper?(send_node)
end
add_offense_to_require_nodes(require_nodes)
end
private
def spec_file?(file_path)
file_path.end_with?("_spec.rb")
end
def require_rails_helper?(send_node)
send_node.command?(:require) && rails_helper?(send_node.first_argument)
end
def rails_helper?(arg_node)
arg_node.str_type? && ["rails_helper"].include?(arg_node.value)
end
def add_offense_to_require_nodes(nodes)
nodes.each { |node| add_offense(node, message: MSG) }
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment