📎 Webclip
Testing HTML in Phoenix Controllers
The post explains how to test HTML responses in Phoenix controllers with ConnTest helpers, then extends the example by adding ExMachina for test data. It walks through the errors that appear along the way and the code needed to make the tests pass.
Reading notes#
- Phoenix ConnTest helpers can be used to test controller responses, and
html_response/2both checks for a 200 status and returns the HTML body. create_pair/3inserts two posts for the list test, whilebuild_pair/3would be used if database persistence were not needed.- Adding ExMachina requires adding the dependency, listing it in the application, and creating a factory module with
use ExMachina.Ecto, repo: MyBlog.Repo. - The
:postfactory builds aMyBlog.Poststruct, usessequence/2for unique titles, and keeps body and author fixed. - Importing
MyBlog.FactoryinMyBlog.ConnCasemakes the factory functions available to controller tests. - The missing
MyBlog.Poststruct is fixed by generating a Post model and migration withmix phoenix.gen.modelandmix ecto.migrate. - The missing
posts_path/2helper is fixed by adding aresources "/posts", PostController, only: [:index]route and aPostControllerwith anindex/2action. - The controller fetches posts with
Repo.all(Post)and renders them withrender(conn, "index.html", posts: posts). - The missing view and template are fixed by adding
PostViewand anindex.html.eextemplate that iterates over@postsand outputspost.title. - For tagged posts, the factory adds
:tagand:post_tagfactories, with:post_tagbuilding a post and a tag by default. - A
tagged_with(post, tag_name)helper creates a tag, creates a post_tag join record, and returns the post. - Using a regular function with ExMachina makes the tagged-post setup easier to reuse and easier to change later.
