Skip to content

Commit

Permalink
Use Floki to find nested fields (#14)
Browse files Browse the repository at this point in the history
In the current version, `fill_form` can't be used if the fields are no
direct children of the form element.
This commit changes the `build_fields` function to use Floki in order to
find all input, select and textarea elements that are somewhere in the
tree of the form element.
  • Loading branch information
Nilsonn authored Feb 8, 2024
1 parent 117bc59 commit 46d6229
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 8 deletions.
12 changes: 5 additions & 7 deletions lib/phoenix_test/html/form.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,11 @@ defmodule PhoenixTest.Html.Form do
end

defp build_fields(fields) do
fields
|> Enum.filter(fn
{"input", _, _} -> true
{"select", _, _} -> true
{"textarea", _, _} -> true
_ -> false
end)
inputs = fields |> Floki.find("input")
selects = fields |> Floki.find("select")
textareas = fields |> Floki.find("textarea")

Enum.concat([inputs, selects, textareas])
|> Enum.map(&create_field/1)
end

Expand Down
18 changes: 18 additions & 0 deletions test/phoenix_test/html/form_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,24 @@ defmodule PhoenixTest.Html.FormTest do

assert %{"type" => "checkbox"} = admin
end

test "parses nested checkbox" do
data =
form_data("""
<form id="user-form" action="/" method="post">
<div>
<label for="admin">Admin</label>
<input type="checkbox" name="admin" />
</div>
</form>
""")

%{"fields" => fields} = Html.Form.parse(data)

admin = Enum.find(fields, &(&1["name"] == "admin"))

assert %{"type" => "checkbox"} = admin
end
end

defp form_data(html_form) do
Expand Down
4 changes: 3 additions & 1 deletion test/phoenix_test/static_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,15 @@ defmodule PhoenixTest.StaticTest do
name: "Aragorn",
admin: "on",
race: "human",
notes: "King of Gondor"
notes: "King of Gondor",
member_of_fellowship: "on"
)
|> click_button("Save")
|> assert_has("#form-data", "name: Aragorn")
|> assert_has("#form-data", "admin: on")
|> assert_has("#form-data", "race: human")
|> assert_has("#form-data", "notes: King of Gondor")
|> assert_has("#form-data", "member_of_fellowship: on")
end

test "raises an error when form cannot be found with given selector", %{conn: conn} do
Expand Down
5 changes: 5 additions & 0 deletions test/support/page_view.ex
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ defmodule PhoenixTest.PageView do
<label for="notes">Notes</label>
<textarea name="notes" rows="5" cols="33">
</textarea>
<div>
<label for="member_of_fellowship">Member of fellowship</label>
<input type="checkbox" name="member_of_fellowship" />
</div>
</form>
"""
end
Expand Down

0 comments on commit 46d6229

Please sign in to comment.