Runs the request against a plug instead of over the network.
This is a Req adapter, used automatically when the :plug option is set.
It requires :plug dependency:
{:plug, "~> 1.0"}Request Options
:plug- the plug to run the request through. It can be one of:A function plug: a
fun(conn)orfun(conn, options)function that takes aPlug.Connand returns aPlug.Conn.A module plug: a
modulename or a{module, options}tuple.
Req automatically calls
Plug.Conn.fetch_query_params/2before your plug, so you can get query params usingconn.query_params.Req also automatically parses request body using
Plug.Parsersfor JSON, urlencoded and multipart requests and you can access it withconn.body_params. The raw request body of the request is available by callingReq.Test.raw_body/1with theconnin your tests.
Examples
This step is particularly useful to test plugs:
defmodule Echo do
def call(conn, _) do
"/" <> path = conn.request_path
Plug.Conn.send_resp(conn, 200, path)
end
end
test "echo" do
assert Req.get!("http:///hello", plug: Echo).body == "hello"
endYou can define plugs as functions too:
test "echo" do
echo = fn conn ->
"/" <> path = conn.request_path
Plug.Conn.send_resp(conn, 200, path)
end
assert Req.get!("http:///hello", plug: echo).body == "hello"
endwhich is particularly useful to create HTTP service stubs, similar to tools like Bypass.
When testing JSON APIs, it's common to use the Req.Test.json/2 helper:
test "JSON" do
plug = fn conn ->
Req.Test.json(conn, %{message: "Hello, World!"})
end
resp = Req.get!(plug: plug)
assert resp.status == 200
assert resp.headers["content-type"] == ["application/json; charset=utf-8"]
assert resp.body == %{"message" => "Hello, World!"}
endYou can simulate network errors by calling Req.Test.transport_error/2
in your plugs:
test "network issues" do
plug = fn conn ->
Req.Test.transport_error(conn, :timeout)
end
assert Req.get(plug: plug, retry: false) ==
{:error, %Req.TransportError{reason: :timeout}}
end