Testing - Asserting Template and Layout
I consider testing one of the most important phase in application development and Rails does a very good job on that. However, testing documentation on Rails Guides is still work under development.
Here is a short tutorial on how you can test that a reponse has rendered the correct template and the correct layout.
If you want to make sure that the response rendered the correct template and layout, you can use the assert_template method:
test “index should render correct template and layout” do
assert_template :layout => “layouts/application”
Note that you cannot test for template and layout at the same time, with one call to assert_template method. Also, for the layout test, you can give a regular expression instead of a string, but using the string, makes things clearer. On the other hand, you have to include the “layouts” directory name even if you save your layout file in this standard layout directory. Hence,
assert_template :layout => “application”
will not work.
Gotcha: Watch out if your view renders any partial
If your view renders any partial, when asserting for the layout, you have to assert for the partial at the same time. Otherwise, assertion will fail.
test “new should render correct layout” do
assert_template :layout => “layouts/application”, :partial => “_form”
is the correct way to assert for the layout when the view renders a partial with name _form. Omitting the :partial key in your assert_template call will complain.
Yesterday, March 24th, I tried to commit the above as my first improvement on Rails Guides, testing guide. Let us see whether this will make it through.