PSPDFKit-labs / bypass

Bypass provides a quick way to create a custom plug that can be put in place instead of an actual HTTP server to return prebaked responses to client requests.
https://hex.pm/packages/bypass
MIT License
964 stars 111 forks source link

Add `Bypass.stub/2` #125

Closed aaronrenner closed 5 months ago

aaronrenner commented 2 years ago

This adds Bypass.stub/2 as a version of Bypass.expect/2 that does not require any requests to be made.

Purpose

I love how easy it is to spin up a dynamic HTTP server with Bypass, but I've found sometimes it's easier to use Plug.Router to build a reusable backend that holds state instead of bypass.

defmodule MySimulator.Router do
  use Plug.Router

  def stub_responses(bypass) do
    Bypass.stub(server.bypass, :any, :any, fn conn ->
      call(conn, init([])
    end)
  end

  plug :match
  plug :fetch_query_params

  plug Plug.Parsers,
    parsers: [:json],
    pass: ["application/json"},
    json_decoder: Jason

  plug :dispatch

  post "/my_route" #...
  post "/my_other_route" #...
end

This currently works, but passing :any for the HTTP Method and Path is undocumented and causes dialyzer warnings. After some testing, I noticed both the HTTP Method and Path have to be set to :any or the server errors.

The fix

I really like Bypass.expect/2 because it allows you to stub any method and path, but I need something that's OK if it isn't called. It seems like Bypass.stub/2 makes sense. I also added tests for this function to ensure it continues to work.

edennis commented 2 years ago

This would be a great addition. 👍🏻