Path: | lib/test/rails/view_test_case.rb |
Last Update: | Fri Jul 03 23:57:03 -0600 2009 |
ViewTestCase allows views to be tested independent of their controllers. Testcase implementors must set up the instance variables the view needs to render itself.
The test class must be named after your controller class name, so if you‘re testing views for the RouteController you would name your test case RouteViewTest. The test case will expect to find your view files in app/views/route.
The test names should be in the form of test_view_edgecase where ‘view’ corresponds to the name of the view file, and ‘edgecase’ describes the scenario you are testing.
If you are testing a view file named ‘show.rhtml’ your test should be named test_show. If your view is behaves differently depending upon its parameters then you can make the test name descriptive like test_show_photos and test_show_no_photos.
class RouteViewTest < Test::Rails::ViewTestCase fixtures :users, :routes, :points, :photos def test_delete # Set up instance variables for template assigns[:loggedin_user] = users(:herbert) assigns[:route] = routes(:work) # render template for the delete action in RouteController render # assert that there's a form with an action of "/route/destroy" assert_form form_url, :post do # with a hidden id field assert_input :hidden, :id # And a submit button that says 'Delete!' assert_submit 'Delete!' end # And a link back to the route so you don't delete it assert_links_to "/route/show/#{routes(:work).id}", 'No, I do not!' end end
require 'test/test_helper' # Create a dummy controller for layout views. This lets the setup use the # right path with minimum fuss. class LayoutsController < ApplicationController; end class LayoutsViewTest < Test::Rails::ViewTestCase fixtures :users, :routes, :points, :photos def test_default # Template set-up @request.request_uri = '/foo' assigns[:action_title] = 'Hello & Goodbye' # Render an empty string with the 'application' layout. render :text => '', :layout => 'application' # Assert content just like a regular view test. assert_links_to '/', 'Home' assert_links_to '/user', 'Login' deny_links_to '/user/logout', 'Logout' assert_title 'Hello & Goodbye' assert_h 1, 'Hello & Goodbye' end end
Form assertions are now using assert_select, so you don‘t need to pass URLs around everywhere and can instead use a block. (See above example).
The form assertions will still work using the old syntax, but in a future release they will give warnings, then will be removed.