Generating separate tests with for - how to make a controller test to validate mandatory fields?

Hi everyone!
I need make a controller tests to validate mandatory fields. In this case the tests is the same for all fieds and the validation too.
Use a loop to generate the same test for different values is wrong?

Enum.each(["document_number", "name", "percentage_share"], fn attribute ->
  @attribute attribute
  @tag new_setup: true
  test "returns error to #{@attribute} when send subject financial account authorization request",
      %{
        partner_conn: partner_conn,
        subject_cnpj_attrs: subject_cnpj_attrs
      } do

    subject_cnpj_attrs =
      Map.merge(subject_cnpj_attrs, %{
      "company_name" => "teste",
      "social_name" => "teste",
      "creation_date" => "2015-04-01",
      "address_street" => "rua antonio pontes filho",
      "address_number" => "310",
      "address_postal_code" => "16201220",
      "address_city" => "santana",
      "address_state" => "FP",
      "address_country" => "montreal",
      "net_monthly_average_income" => 4000,
    })

    documents = [
      %{
        "file_type" => "application/pdf",
        "file_url" => "social-contract-url",
        "labels" => ["social-contract"]
      }
    ]

    partners = [ %{"address_country" => "franca"} ]

    [partner_1, partner_2] = partners
    partner_1 = Map.delete(partner_1, @attribute)

    subject_cnpj_attrs =
      Map.merge(subject_cnpj_attrs, %{"documents" => documents})
      |> Map.merge(%{"partners" => [partner_1, partner_2]})

    subject =
      partner_conn
      |> create_company(subject_cnpj_attrs)
      |> json_response(422)
      |> Map.get("errors")

    assert %{"partners" => [%{"#{@attribute}" => ["can't be blank"]}, %{}]} == subject
  end
end)

That should work. You’ll want to unquote(attribute) in the body of the test though.

This article helped me when writing tests this way: 🐥 Parameterized tests in Elixir ExUnit | 🐥 YellowDuck.be

2 Likes