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)

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

Constant Summary collapse

MSG =
'Prefer `expect(response).%<to>s have_http_status(%<status>i)` ' \
'over `expect(response.status).%<to>s %<match>s`.'

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_pattern, #send_pattern

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?

Instance Method Details

#match_status(node) ⇒ Object


24
25
26
27
28
29
30
31
32
# File 'lib/rubocop/cop/rspec/rails/have_http_status.rb', line 24

def_node_matcher :match_status, <<-PATTERN
  (send
    (send nil? :expect
      $(send (send nil? :response) :status)
    )
    $#Runners.all
    $(send nil? {:be :eq :eql :equal} (int $_))
  )
PATTERN

#on_send(node) ⇒ Object


34
35
36
37
38
39
40
41
42
# File 'lib/rubocop/cop/rspec/rails/have_http_status.rb', line 34

def on_send(node)
  match_status(node) do |response_status, to, match, status|
    message = format(MSG, to: to, match: match.source, status: status)
    add_offense(node, message: message) do |corrector|
      corrector.replace(response_status.source_range, 'response')
      corrector.replace(match.loc.selector, 'have_http_status')
    end
  end
end