现在的位置: 首页 > 综合 > 正文

Ruby on rails开发从头来(windows)(二十四)-测试Controller

2011年02月12日 ⁄ 综合 ⁄ 共 2559字 ⁄ 字号 评论关闭
上篇随笔里介绍了rails在功能测试方面的一些约定。这次我们继续会到Controller的测试。
之前我们测试的是login,可以相见,用户在login以后就要开始进行购物的动作了,所以我们现在就来测试store_controller,我们先来测试index方法。

1.       index里,我们列出了所有的可以销售的书籍的列表,所以,这里我们要让store_controller来使用product.ymlorders.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; end

 

class StoreControllerTest < Test::Unit::TestCase

fixtures :products, :orders

def setup

@controller = StoreController.new

@request    = ActionController::TestRequest.new

@response   = ActionController::TestResponse.new

end

 

# Replace this with your real tests.

def teardown

    LineItem.delete_all

end

end

要注意到我们这里的teardown方法,添加这个方法是因为我们将要写的一些测试会间接的将一些LineItem存入数据库中。在所有的测试方法后面定义这个teardown方法,可以很方便的在测试执行后删除测试数据,这样就不会影响到其他的测试。在调用了LineItem.delete_all之后,line_item表中所有的数据都会被删除。通常情况下,我们不需要这样作,因为fixture会替我们清除数据,但是这里,我们没有使用line_itemfixture,所以我们要自己来作这件事情。

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

def test_index

    get :index

    assert_response :success

    assert_equal 2, assigns(:products).size

    assert_template "store/index"

  end

因为我们在前面的Model的测试里已经测试了ProductsCRUD,所以这里,我们测试indexAction,并且看看Products的个数,是不是使用了指定的View来描画(render)页面。

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

3.       测试add_to_cart方法:

在测试类里添加方法:

def test_add_to_cart

get :add_to_cart, :id => @version_control_book.id

cart = session[:cart]

assert_equal @version_control_book.price, cart.total_price

assert_redirected_to :action => 'display_cart'

follow_redirect

assert_equal 1, assigns(:items).size

assert_template "store/display_cart"

end

然后运行测试,如果你和我一样不幸的话,会提示@version_control_book对象为nil,这个问题是以前在测试ProductModel时遗留的问题,为了不影响学习的大计,这个地方我们给改改,好让这个系列能继续:

def test_add_to_cart

    @product = Product.find(1)

get :add_to_cart, :id => @product.id

cart = session[:cart]

assert_equal @product.price, cart.total_price

assert_redirected_to :action => 'display_cart'

follow_redirect

assert_equal 1, assigns(:items).size

assert_template "store/display_cart"

end

标示为蓝色的代码是我们修改的地方,再次运行测试看看:

Finished in 0.156 seconds.

2 tests, 7 assertions, 0 failures, 0 errors

嗯,测试全部通过。

在这里要注意在页面的重定向的断言后,调用了follow_redirect,这是模拟浏览器重定向到一个新的页面。这样做是让assign是可变的,并且,assert_template断言使用display_cart Action的结果,而不是之前的add_to_cart的结果,这样,display_cartAction会描画display_cart.html视图。

4.       下面我们继续测试用户向购物车中添加一个不存在的product的情况,因为用户可能直接在浏览器地址栏中输入地址,导致一个不存在的productid,添加test_add_to_cart_invalid_product方法:

def test_add_to_cart_invalid_product

get :add_to_cart, :id => '-1'

assert_redirected_to :action => 'index'

assert_equal "Invalid product", flash[:notice]

end

运行测试,成功了。

 

好了,这次就到这里。

抱歉!评论已关闭.