- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3 (0)
- 2.1.0 (38)
- 2.2.1 (0)
- 2.3.8 (0)
- 3.0.0 (0)
- 3.0.9 (0)
- 3.1.0 (0)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
One thing that has always been a pain with remote web services is testing. The HttpMock class makes it easy to test your Active Resource models by creating a set of mock responses to specific requests.
To test your Active Resource model, you simply call the ActiveResource::HttpMock.respond_to method with an attached block. The block declares a set of URIs with expected input, and the output each request should return. The passed in block has any number of entries in the following generalized format:
mock.http_method(path, request_headers = {}, body = nil, status = 200, response_headers = {})
-
http_method - The HTTP method to listen for. This can be get, post, put, delete or head.
-
path - A string, starting with a “/”, defining the URI that is expected to be called.
-
request_headers - Headers that are expected along with the request. This argument uses a hash format, such as { "Content-Type" => "application/json" }. This mock will only trigger if your tests sends a request with identical headers.
-
body - The data to be returned. This should be a string of Active Resource parseable content, such as Json.
-
status - The HTTP response code, as an integer, to return with the response.
-
response_headers - Headers to be returned with the response. Uses the same hash format as request_headers listed above.
In order for a mock to deliver its content, the incoming request must match by the http_method, path and request_headers. If no match is found an InvalidRequestError exception will be raised showing you what request it could not find a response for and also what requests and response pairs have been recorded so you can create a new mock for that request.
Example
def setup @matz = { :person => { :id => 1, :name => "Matz" } }.to_json ActiveResource::HttpMock.respond_to do |mock| mock.post "/people.json", {}, @matz, 201, "Location" => "/people/1.json" mock.get "/people/1.json", {}, @matz mock.put "/people/1.json", {}, nil, 204 mock.delete "/people/1.json", {}, nil, 200 end end def test_get_matz person = Person.find(1) assert_equal "Matz", person.name end