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.Router
plug :match
plug ValidateExternalService
plug :dispatch
match _, via: [:get, :post, :delete, :put] do
send_resp(conn, 200, "")
end
end
defmodule 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 do
import Plug.Conn
def init(opts) do
opts
end
def 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?