Testing Views and Templates

As we’ve said, any code worth writing is code worth testing, and your views are no exception. As you saw in Chapter 3, Controllers, Phoenix templates are simply functions in a parent’s view module. You can test these functions like any other. In this section, you’ll see how to test views and templates in isolation.

Create a test/rumbl_web/views/video_view_test.exs and key this in:

1: defmodule​ RumblWeb.VideoViewTest ​do
use​ RumblWeb.ConnCase, ​async:​ true
import​ Phoenix.View
5:  test ​"​​renders index.html"​, %{​conn:​ conn} ​do
videos = [
%Rumbl.Multimedia.Video{​id:​ ​"​​1"​, ​title:​ ​"​​dogs"​},
%Rumbl.Multimedia.Video{​id:​ ​"​​2"​, ​title:​ ​"​​cats"​}
]
10: 
content = render_to_string(
RumblWeb.VideoView,
"​​index.html"​,
conn:​ conn,
15: videos:​ videos)
assert String.contains?(content, ​"​​Listing Videos"​)
for video <- videos ​do
20:  assert String.contains?(content, video.title)
end
end
test ​"​​renders new.html"​, %{​conn:​ conn} ​do
25:  owner = %Rumbl.Accounts.User{}
changeset = Rumbl.Multimedia.change_video(%Rumbl.Multimedia.Video{})
categories = [%Rumbl.Multimedia.Category{​id:​ 123, ​name:​ ​"​​cats"​}]
content =
30:  render_to_string(RumblWeb.VideoView, ​"​​new.html"​,
conn:​ conn,
changeset:​ changeset,
categories:​ categories
)
35: 
assert String.contains?(content, ​"​​New Video"​)
end
end

Our test needs some videos, so on line 5, we set up our required @videos assigns. With all of the prerequisites in place, we call Phoenix.View.render_to_string to render our HTML template as a simple string. Then, we make sure that all of the video titles are present on the page.

On line 24, we again set up our necessary @changeset and @categories assigns before rendering our template as a string and asserting that our render contents place us on the new video page.

Sometimes, views are simple enough that your integration tests will be enough. Many other times, you won’t test the templates directly, but the functions that you create to help move the logic away from the templates and into code. Our goal with this section is to once again highlight the fact that because a template is just a function in the view, templates are easy to test because they aren’t coupled with the controller layer. And this will apply to any function you create in your view, because all arguments are received explicitly. With Phoenix, you’ll have all of the tools you need to do so easily. We’ve covered a lot of ground so it’s a good time to wrap up.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.41.235