Welcome 微信登录

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

Ruby on rails开发从头来(windows)(十九)-测试开始2011-12-02 博客园 Cure前面我们已经完成了一个简单的购物车,从这篇开始我们看看在rails中怎样进行测试。

在我们创建购物车程序的时候在我们的depot目录下,就已经有一个test目录了,这就是为我们进行测试准备的。到目前为止,我们看到里面的fixtrues和functional,unit目录中已经有对controller和model对应的测试文件。

我们首先测试一下products这个model。代码testunit目录下的product_test.rb文件,修改其内容为:

require File.dirname(__FILE__) + "/../test_helper"  class ProductTest < Test::Unit::TestCase fixtures :products def setup  @product = Product.find(1) end # Replace this with your real tests. def test_truth  assert true endend
然后在命令行里运行测试命令: ails_appsdepot>ruby test/unit/product_test.rb,将会看到下面的输出:

Loaded suite test/unit/product_testStartedEFinished in 0.312 seconds.  1) Error:test_truth(ProductTest):ActiveRecord::StatementInvalid: Mysql::Error: Table "depot_test.products" doesn"t exist: DELETE FROM products………1 tests, 0 assertions, 0 failures, 1 errors
从上面的信息可以看到,是在depot_test数据库中没有products这个表。这是因为,我们在创建一个rails项目的时候,对应的在mysql中创建了三个库:development,test,production,我们之前编写代码使用的都是development库,现在进行测试,rails使用的是test库。我们现在要作的就是在test库里创建products表,你可以使用sql语句来进行表创建的工作,但是rails给我们提供了更方便的办法,在命令行里使用rake命令:

depot>rake clone_structure_to_test
这样就会development库的结构克隆到test库,完成后会看到在test库里已经有我们用到的四个表了。