aboutsummaryrefslogtreecommitdiffstats
path: root/activeresource/test/http_mock.rb
blob: a4bc7e7cb2b46b999528394193ab77ce90286ff5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
require 'active_resource/connection'

module ActiveResource
  class HttpMock
    class << self
      def requests
        @@requests ||= []
      end

      def responses
        @@responses ||= {}
      end

      def respond_to(pairs)
        reset!
        pairs.each do |(path, response)|
          responses[path] = response
        end
      end

      def reset!
        requests.clear
        responses.clear
      end
    end

    for method in [ :post, :put, :get, :delete ]
      module_eval <<-EOE
        def #{method}(*arguments)
          request = ActiveResource::Request.new(:#{method}, *arguments)
          self.class.requests << request
          self.class.responses[request] || raise("No response recorded for: \#{request}")
        end
      EOE
    end
    
    def initialize(site)
      @site = site
    end
  end

  class Request
    attr_accessor :path, :method, :body
    
    def initialize(method, path, body = nil)
      @method, @path, @body = method, path, body
    end

    def ==(other_request)
      other_request.hash == hash
    end
    
    def eql?(other_request)
      self == other_request
    end
    
    def to_s
      "<#{method.to_s.upcase}: #{path} (#{body})>"
    end
    
    def hash
      "#{path}#{method}".hash
    end
  end
  
  class Response
    attr_accessor :body, :code
    
    def initialize(body, code = 200)
      @body, @code = body, code
    end
    
    def success?
      (200..299).include?(code)
    end
  end

  class Connection
    private
      def http
        @http ||= HttpMock.new(@site)
      end
  end
end