I am doing a test with Phoenix Live View:
assert view
|> form("#new_product", product: %{name: nil})
|> render_change() =~ "can't be blank"
But the test did not accept the assertion.
So changing the string "can't be blank"
for "can't be blank"
will work the assertion.
I know this is something about the Unicode generated in the HTML.
But I would like to use the 1st string.
What I need to do was import the Phoenix HTML: import Phoenix.HTML
and now pipe the string with the functions html_escape()
and safe_to_string()
:
assert view
|> form("#new_product", product: %{name: nil})
|> render_change() =~ "can't be blank" |> html_escape() |> safe_to_string()
1 Like
To be precise, this has nothing to do with Unicode. What you’re seeing are HTML entities, special encodings used for HTML-specific characters: HTML Character Entities
Personally, I almost always use Floki (installed by default with Phoenix) for this kind of tests. I parse the document, select the elements I’m interested in, and extract their textual content (which is already HTML-decoded). It looks like this:
assert view
|> form("#new_product", product: %{name: nil})
|> render_change()
|> Floki.parse_document!()
|> Floki.find("span.invalid-feedback")
|> Floki.text() =~ "can't be blank"
4 Likes
=~
does a plain match of text. It’s unanware that the left side is encoded html (it’s still UTF-8). You can either go and make your expected string also encoded (as you did) or adjust the other side by decoding the html to plain strings, as @trisolaran did with html |> Floki.parse_document!() |> Floki.text()
.
3 Likes
Thank you all it was very helpful!
Another question guys, if I do for example a function for use globally this to other test files.
where is the best place to put it?
I was trying the data_case.ex
.
I can create the:
html_entities_parse(string) do
string
|> html_escape()
|> safe_to_string()
end