Class: RuboCop::Cop::RSpec::Rails::HaveHttpStatus

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rspec/rails/have_http_status.rb

Overview

Checks that tests use ‘have_http_status` instead of equality matchers.

Examples:

# bad
expect(response.status).to be(200)
expect(response.code).to eq("200")

# good
expect(response).to have_http_status(200)

Constant Summary collapse

MSG =
'Prefer `expect(response).%<to>s have_http_status(%<status>s)` ' \
'over `%<bad_code>s`.'
RUNNERS =
%i[to to_not not_to].to_set
RESTRICT_ON_SEND =
RUNNERS

Instance Method Summary collapse

Instance Method Details

#match_status(node) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/rubocop/cop/rspec/rails/have_http_status.rb', line 28

def_node_matcher :match_status, <<-PATTERN
  (send
    (send nil? :expect
      $(send (send nil? :response) {:status :code})
    )
    $RUNNERS
    $(send nil? {:be :eq :eql :equal} ({int str} $_))
  )
PATTERN

#on_send(node) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rubocop/cop/rspec/rails/have_http_status.rb', line 38

def on_send(node)
  match_status(node) do |response_status, to, match, status|
    return unless status.to_s.match?(/\A\d+\z/)

    message = format(MSG, to: to, status: status,
                          bad_code: node.source)
    add_offense(node, message: message) do |corrector|
      corrector.replace(response_status, 'response')
      corrector.replace(match.loc.selector, 'have_http_status')
      corrector.replace(match.first_argument, status.to_s)
    end
  end
end