---
title: "Shoulda教程之四—测试控制器"
author: "chenk85"
date: "2008-05-18T02:02:02Z"
tags: []
slug: "shoulda"
draft: false
lastmod: "2008-05-18T02:02:02Z"
id: 209275
url: "https://chenk85.iteye.com/blog/209275"
---

控制器 基本的控制助手方法 如ActiveRecord宏一样，Shoulda 提供了一套测试控制器的宏，以尽可能简洁的方法进行测试。所有的这些方法都在Shoulda的Rdoc中，但这里再送上一个快捷的例子： class UsersControllerTest &lt; Test::Unit::TestCase   context "on GET to :show" do     setup { get :show, :id =&gt; 1 }        should\_assign\_to :user     should\_respond\_with :success     should\_render\_template :show     should\_not\_set\_the\_flash        should "do something else really cool" do       assert\_equal 1, assigns(:user).id     end   end      context "on POST to :create" do     setup { post :create, :user =&gt; {:name =&gt; 'Ronald', :party =&gt; 'Repukeulan' } }     should\_assign\_to :user     should\_redirect\_to "user\_url(@user)"     should\_set\_the\_flash\_to(/created/i)   end end 应该RESTful 这里每个 should\_xxx 宏都会产生一个单独的测试方法，编写起来又DRY。而should\_be\_restful 宏可以产生遵循基本的RESTful设计模式的控制器。should\_be\_restful 宏就像一个超级测试生成器，每次调用是都会产生40到50个测试方法。这里有个超简单的例子： class UsersControllerTest &lt; Test::Unit::TestCase   def \[...]