XUtils

bypass

Bypass provides a quick way to create a mock HTTP server with a custom plug.


Expect Functions

You can take any of the following approaches:

  • expect/2 or expect_once/2 to install a generic function that all calls to bypass will use
  • expect/4 and/or expect_once/4 to install specific routes (method and path)
  • stub/4 to install specific routes without expectations
  • a combination of the above, where the routes will be used first, and then the generic version will be used as default

How to use with ESpec

While Bypass primarily targets ExUnit, the official Elixir builtin test framework, it can also be used with ESpec. The test configuration is basically the same, there are only two differences:

  1. In your Mix config file, you must declare which test framework Bypass is being used with (defaults to :ex_unit). This simply disables the automatic integration with some hooks provided by ExUnit.
   config :bypass, test_framework: :espec
  1. In your specs, you must explicitly verify the declared expectations. You can do it in the finally block.
   defmodule TwitterClientSpec do
     use ESpec, async: true

     before do
       bypass = Bypass.open()
       {:shared, bypass: bypass}
     end

     finally do
       Bypass.verify_expectations!(shared.bypass)
     end

     specify "the client can handle an error response" do
       Bypass.expect_once(shared.bypass, "POST", "/1.1/statuses/update.json", fn conn ->
         Plug.Conn.resp(conn, 429, ~s<{"errors": [{"code": 88, "message": "Rate limit exceeded"}]}>)
       end)

       {:ok, client} = TwitterClient.start_link(url: endpoint_url(shared.bypass.port))
       assert {:error, :rate_limited} == TwitterClient.post_tweet(client, "Elixir is awesome!")
     end

     defp endpoint_url(port), do: "http://localhost:#{port}/"
   end

Configuration options

Set :enable_debug_log to true in the application environment to make Bypass log what it’s doing:

config :bypass, enable_debug_log: true

Articles

  • coming soon...