Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选

首页 / 软件开发 / JAVA / Ruby on rails开发从头来(windows)(二十四)-测试Controller

Ruby on rails开发从头来(windows)(二十四)-测试Controller2011-12-02 博客园 Cure上篇随笔里介绍了rails在功能测试方面的一些约定。这次我们继续会到Controller的测试。

之前我们测试的是login,可以相见,用户在login以后就要开始进行购物的动作了,所以我们现在就来测试store_controller,我们先来测试index方法。

1.在index里,我们列出了所有的可以销售的书籍的列表,所以,这里我们要让store_controller来使用product.yml和orders.yml里的数据。现在来看看store_controller_test.rb文件,完整内容如下:

require File.dirname(__FILE__) + "/../test_helper"require "store_controller"# Re-raise errors caught by the controller.class StoreController; def rescue_action(e) raise e end; endclass StoreControllerTest < Test::Unit::TestCasefixtures :products, :ordersdef setup@controller = StoreController.new@request  = ActionController::TestRequest.new@response  = ActionController::TestResponse.newend# Replace this with your real tests.def teardown  LineItem.delete_allendend
要注意到我们这里的teardown方法,添加这个方法是因为我们将要写的一些测试会间接的将一些LineItem存入数据库中。在所有的测试方法后面定义这个teardown方法,可以很方便的在测试执行后删除测试数据,这样就不会影响到其他的测试。在调用了LineItem.delete_all之后,line_item表中所有的数据都会被删除。通常情况下,我们不需要这样作,因为fixture会替我们清除数据,但是这里,我们没有使用line_item的fixture,所以我们要自己来作这件事情。

2.接下来我们添加一个test_index方法:

def test_index  get :index  assert_response :success  assert_equal 2, assigns(:products).size  assert_template "store/index" end
因为我们在前面的Model的测试里已经测试了Products的CRUD,所以这里,我们测试index的Action,并且看看Products的个数,是不是使用了指定的View来描画(render)页面。

我们在Controller中使用了Model,如果Controller的测试失败了,而Model的测试通过了,那么一般就要在Controller中查找问题,如果Controller和Model的测试都失败了,那么我们最好在Model中查找问题。