Skip to content

Instantly share code, notes, and snippets.

@clekstro
Last active September 24, 2015 22:30
Show Gist options
  • Save clekstro/ff5b7bb99cd4760191db to your computer and use it in GitHub Desktop.
Save clekstro/ff5b7bb99cd4760191db to your computer and use it in GitHub Desktop.
Issue testing halting behavior of plugs

I’m having issues testing that a plug is properly halting the pipeline when an external service returns an error. ​ Here's the test, which ensures we call our plug under test: ​

defmodule HaltTestApp do
  use Plug.Routerplug :match
  plug ValidateExternalServiceplug :dispatchmatch _, via: [:get, :post, :delete, :put] do
    send_resp(conn, 200, "")
  end
enddefmodule ValidateExternalServiceTest do
  use ExUnit.Case, async: true
  use Plug.Test@opts HaltTestApp.init([])
  
  @post_body %{foo: "bar"}
   test "resource already exists" do
    conn = conn(:post, "http://blah.foo/validate", @post_body) |> put_status(409)
    HaltTestApp.call(conn, [])
    assert conn.status == 409
    assert conn.halted
  end
end

​ The plug under test should halt the pipeline if it encounters an error from the external service, returning the server error code to the client: ​

defmodule ValidateExternalService doimport Plug.Conndef init(opts) do
    opts
  enddef call(conn, _opts) do
    case conn.status do
      201 -> conn
      _ -> conn |> halt
    end
  end
end

​ I can see that we correctly hit the code that says that the execution should be halted, but conn.halted continues to return false. ​ Is there an alternative way to test this? Is this behavior expected?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment