Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HaveHTTPStatus matcher #378

Merged
merged 1 commit into from Mar 4, 2020
Merged

Add HaveHTTPStatus matcher #378

merged 1 commit into from Mar 4, 2020

Conversation

ansd
Copy link
Collaborator

@ansd ansd commented Feb 16, 2020

Add new HaveHTTPStatus matcher to easily test HTTP status of an HTTP response (recorder).

Inspired by https://relishapp.com/rspec/rspec-rails/v/3-9/docs/matchers/have-http-status-matcher.

Design discussions:

  1. Allow ACTUAL to be either a *http.Response or *httptest.ResponseRecorder.
    When unit test-driving a server, a *httptest.ResponseRecorder will probably be used.
    When writing integration tests, a *http.Response will be used.
  2. Allow EXPECTED to be an int or a string such that either the StatusCode or Status field can be matched.

A working example demonstrating these different use cases:

package resp_test

import (
	"net/http"
	"net/http/httptest"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("HaveHTTPStatus", func() {
	It("works on *http.Response", func() {
		resp, err := http.Get("http://www.google.com")

		Expect(err).NotTo(HaveOccurred())
		Expect(resp).To(HaveHTTPStatus(http.StatusOK))
		Expect(resp).To(HaveHTTPStatus("200 OK"))
	})

	It("works on *httptest.ResponseRecorder", func() {
		req, err := http.NewRequest(http.MethodGet, "some URL", nil)
		Expect(err).NotTo(HaveOccurred())

		rr := httptest.NewRecorder()
		h := http.HandlerFunc(someHandler)
		h.ServeHTTP(rr, req)

		Expect(rr).To(HaveHTTPStatus(http.StatusOK))
		Expect(rr).To(HaveHTTPStatus("200 OK"))
	})
})

func someHandler(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
}

Co-authored-by: David Ansari <dansari@pivotal.io>
@ansd ansd requested a review from blgm February 16, 2020 15:28
This was referenced Feb 16, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants