Flowdock
respond_to(*args) public

Accepts a block which declares a set of requests and responses for the HttpMock to respond to in the following format:

mock.http_method(path, request_headers = {}, body = nil, status = 200, response_headers = {})

Example

@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

Alternatively, accepts a hash of {Request => Response} pairs allowing you to generate these the following format:

ActiveResource::Request.new(method, path, body, request_headers)
ActiveResource::Response.new(body, status, response_headers)

Example

Request.new(:#{method}, path, nil, request_headers)

@matz  = { :person => { :id => 1, :name => "Matz" } }.to_json

create_matz      = ActiveResource::Request.new(:post, '/people.json', @matz, {})
created_response = ActiveResource::Response.new("", 201, {"Location" => "/people/1.json"})
get_matz         = ActiveResource::Request.new(:get, '/people/1.json', nil)
ok_response      = ActiveResource::Response.new("", 200, {})

pairs = {create_matz => created_response, get_matz => ok_response}

ActiveResource::HttpMock.respond_to(pairs)

Note, by default, every time you call respond_to, any previous request and response pairs stored in HttpMock will be deleted giving you a clean slate to work on.

If you want to override this behavior, pass in false as the last argument to respond_to

Example

ActiveResource::HttpMock.respond_to do |mock|
  mock.send(:get, "/people/1", {}, "JSON1")
end
ActiveResource::HttpMock.responses.length #=> 1

ActiveResource::HttpMock.respond_to(false) do |mock|
  mock.send(:get, "/people/2", {}, "JSON2")
end
ActiveResource::HttpMock.responses.length #=> 2

This also works with passing in generated pairs of requests and responses, again, just pass in false as the last argument:

Example

ActiveResource::HttpMock.respond_to do |mock|
  mock.send(:get, "/people/1", {}, "JSON1")
end
ActiveResource::HttpMock.responses.length #=> 1

get_matz         = ActiveResource::Request.new(:get, '/people/1.json', nil)
ok_response      = ActiveResource::Response.new("", 200, {})

pairs = {get_matz => ok_response}

ActiveResource::HttpMock.respond_to(pairs, false)
ActiveResource::HttpMock.responses.length #=> 2

# If you add a response with an existing request, it will be replaced

fail_response      = ActiveResource::Response.new("", 404, {})
pairs = {get_matz => fail_response}

ActiveResource::HttpMock.respond_to(pairs, false)
ActiveResource::HttpMock.responses.length #=> 2
Show source
Register or log in to add new notes.