diff --git a/README.md b/README.md index 53e83e2eec..19c12f271a 100644 --- a/README.md +++ b/README.md @@ -296,6 +296,8 @@ The `payload` is a `Hash` with the following keys: * `method` as a `Symbol` * `request_uri` as a `String` +* `headers` as a `Hash` +* `body` as a `String` when available * `result` as an `Net::HTTPResponse` ## License diff --git a/lib/active_resource/connection.rb b/lib/active_resource/connection.rb index 1f17057ad5..a611225ba5 100644 --- a/lib/active_resource/connection.rb +++ b/lib/active_resource/connection.rb @@ -116,9 +116,13 @@ def head(path, headers = {}) private # Makes a request to the remote service. def request(method, path, *arguments) + body, headers = arguments + headers, body = body, nil if headers.nil? result = ActiveSupport::Notifications.instrument("request.active_resource") do |payload| payload[:method] = method payload[:request_uri] = "#{site.scheme}://#{site.host}:#{site.port}#{path}" + payload[:headers] = headers + payload[:body] = body payload[:result] = http.send(method, path, *arguments) end handle_response(result) diff --git a/test/cases/notifications_test.rb b/test/cases/notifications_test.rb new file mode 100644 index 0000000000..c3e6c898d4 --- /dev/null +++ b/test/cases/notifications_test.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +require "abstract_unit" +require "fixtures/person" + +class NotificationsTest < ActiveSupport::TestCase + def setup + matz = { person: { id: 1, name: "Matz" } } + @people = { people: [ matz ] }.to_json + @default_request_headers = { "Content-Type" => "application/json" } + + ActiveResource::HttpMock.respond_to do |mock| + mock.get "/people.json?name=Matz", { "Accept" => "application/json" }, @people + mock.post "/people.json", { "Content-Type" => "application/json" }, nil, 201, "Location" => "/people/5.json" + end + end + + def test_get_request_with_params + payload = capture_notifications { Person.where(name: "Matz") } + + assert_equal :get, payload[:method] + assert_equal "http://37s.sunrise.i:3000/people.json?name=Matz", payload[:request_uri] + assert_equal({ "Accept" => "application/json" }, payload[:headers]) + assert_nil payload[:body] + assert_kind_of ActiveResource::Response, payload[:result] + end + + def test_post_request_with_body + payload = capture_notifications { Person.create!(name: "Matz") } + + assert_equal :post, payload[:method] + assert_equal "http://37s.sunrise.i:3000/people.json", payload[:request_uri] + assert_equal({ "Content-Type" => "application/json" }, payload[:headers]) + assert_equal({ "person" => { "name" => "Matz" } }.to_json, payload[:body]) + assert_kind_of ActiveResource::Response, payload[:result] + end + + def capture_notifications(&block) + payload = nil + ActiveSupport::Notifications.subscribed ->(event) { payload = event.payload }, "request.active_resource", &block + payload + end +end