Class: CheckHttpResponse::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/check_http_response/request.rb

Defined Under Namespace

Classes: HttpRequest

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, options) ⇒ Request

Returns a new instance of Request.



12
13
14
15
16
17
# File 'lib/check_http_response/request.rb', line 12

def initialize(url, options)
  @headers = options[:headers] || {}
  @url = url

  clear_errors
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



10
11
12
# File 'lib/check_http_response/request.rb', line 10

def errors
  @errors
end

#headersObject (readonly)

Returns the value of attribute headers.



10
11
12
# File 'lib/check_http_response/request.rb', line 10

def headers
  @headers
end

#urlObject (readonly)

Returns the value of attribute url.



10
11
12
# File 'lib/check_http_response/request.rb', line 10

def url
  @url
end

Instance Method Details

#redirects_to?(location, options = {}) ⇒ Boolean

Returns true if the response redirects to the given location.

Warning: ‘303 see other’ is not supported

response = CheckHttpResponse.for(
  'http://localhost:8080/page/1',
  :headers => { 'Host' => 'www.mydomain.com' }
)
response.redirects_to?('http://www.mydomain.com/page/1/index.html') #=> true

response.redirects_to?('http://nowhere.com/')                       #=> false
response.errors                                                     #=> { :redirect => "Wrong location! Got: http://www.mydomain.com/page/1/index.html , expected: http://nowhere.com/" }

Options

:permanent Specifies whether the redirect should be ‘permanent’, default: true

Returns:

  • (Boolean)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/check_http_response/request.rb', line 34

def redirects_to?(location, options = {})
  clear_errors

  check_permanent = true
  check_permanent = options[:permanent] if not options[:permanent].nil?

  redirected = false
  begin
    HttpRequest.get(self.url,
      :headers => self.headers,
      :no_follow => true
    )

    @errors[:base] = "No redirect initiated"
  rescue HTTParty::RedirectionTooDeep => e
    redirected_location = e.response['location']
    is_correct_location = location == redirected_location

    is_correct_redirect = if check_permanent
                            e.response.class == Net::HTTPMovedPermanently
                          else
                            e.response.class == Net::HTTPFound
                          end

    redirected = is_correct_location && is_correct_redirect
    @errors[:redirect] = "Wrong redirect type!" if not is_correct_redirect
    @errors[:redirect] = "Wrong location! Got: #{redirected_location} , expected: #{location}" if not is_correct_location
  end

  return redirected
end