Class: RuboCop::Cop::Rails::HttpPositionalArguments

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector, TargetRailsVersion
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/rails/http_positional_arguments.rb

Overview

Identifies usages of http methods like get, post, put, patch without the usage of keyword arguments in your tests and change them to use keyword args. This cop only applies to Rails >= 5. If you are running Rails < 5 you should disable the Rails/HttpPositionalArguments cop or set your TargetRailsVersion in your .rubocop.yml file to 4.2.

NOTE: It does not detect any cases where ‘include Rack::Test::Methods` is used which makes the http methods incompatible behavior.

Examples:

# bad
get :new, { user_id: 1}

# good
get :new, params: { user_id: 1 }
get :new, **options

Constant Summary collapse

MSG =
'Use keyword arguments instead of positional arguments for http call: `%<verb>s`.'
KEYWORD_ARGS =
i[method params session body flash xhr as headers env to].freeze
ROUTING_METHODS =
i[draw routes].freeze
RESTRICT_ON_SEND =
i[get post put patch delete head].freeze

Constants included from TargetRailsVersion

TargetRailsVersion::TARGET_GEM_NAME, TargetRailsVersion::USES_REQUIRES_GEM_API

Instance Method Summary collapse

Methods included from TargetRailsVersion

minimum_target_rails_version, support_target_rails_version?

Instance Method Details

#on_send(node) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/rubocop/cop/rails/http_positional_arguments.rb', line 54

def on_send(node)
  return if in_routing_block?(node) || use_rack_test_methods?

  http_request?(node) do |data|
    return unless needs_conversion?(data)

    message = format(MSG, verb: node.method_name)

    add_offense(highlight_range(node), message: message) do |corrector|
      # given a pre Rails 5 method: get :new, {user_id: @user.id}, {}
      #
      # @return lambda of auto correct procedure
      # the result should look like:
      #     get :new, params: { user_id: @user.id }, session: {}
      # the http_method is the method used to call the controller
      # the controller node can be a symbol, method, object or string
      # that represents the path/action on the Rails controller
      # the data is the http parameters and environment sent in
      # the Rails 5 http call
      corrector.replace(node, correction(node))
    end
  end
end