I want to test a endpoint that makes external api calls. What I want to do is to only do this external api call once (generate a payload) and only generate new ones when the tag ;value is provided. Here is my tring but on each test it generates a new payload anyway
defmodule TestesPayTest.BusinessRules do
use ExUnit.Case, async: true
use Plug.Test
require Logger
@create_qr_url "https://sandbox.asaas.com/api/v3/pix/qrCodes/static"
@pix_key "ab09d852-14bd-43ac-91eb-d38b717e6aea"
setup_all do
access_token = System.get_env("ACCESS_TOKEN")
base_fee = 0.0765
basic_ref_fee = 0.0165
payload =
case create_payload(100) do
{:ok, payload} -> payload
{:error, _reason} -> nil
end
:ok = Ecto.Adapters.SQL.Sandbox.checkout(MyApp.Repo)
Ecto.Adapters.SQL.Sandbox.mode(MyApp.Repo, {:shared, self()})
{:ok, %{access_token: access_token, base_fee: base_fee, basic_ref_fee: basic_ref_fee}}
end
setup context do
value = context[:value]
if value do
new_payload =
case create_payload(value) do
{:ok, new_payload} ->
Map.put(context, :payload, new_payload)
{:error, reason} ->
Logger.error("Falha ao criar novo payload: #{inspect(reason)}")
nil
end
end
end
tests
describe "chain invalida" do
@tag value: 630
test "POST /api/create_contract", %{payload: payload} do
Logger.debug("deve ser padrao #{inspect(payload)}")
body = Jason.encode!(%{
"chain" => "qlqr",
"coin" => "ETH",
"payload" => payload
})
conn = conn(:post, "/api/create_contract", body)
|> put_req_header("content-type", "application/json")
|> TestesPay.MyRouter.call(body)
IO.inspect(conn.resp_body)
expected_error = %{
"field" => "chain",
"msg" => "rede invalida"
}
assert conn.status == 400
assert Jason.decode!(conn.resp_body) == expected_error
end
end
describe "coin invalida" do
test "POST /api/create_contract", %{payload: payload} do
Logger.debug("deve ser padrao #{inspect(payload)}")
body = Jason.encode!(%{
"chain" => "eth",
"coin" => "xereb",
"payload" => payload
})
conn = conn(:post, "/api/create_contract", body)
|> put_req_header("content-type", "application/json")
|> TestesPay.MyRouter.call(body)
IO.inspect(conn.resp_body)
expected_error = %{
"field" => "coin",
"msg" => "moeda invalida"
}
assert conn.status == 400
assert Jason.decode!(conn.resp_body) == expected_error
end
end