Rubyonrails开发从头来(windows)(十九)-测试开始

前面我们已经完成了一个简单的购物车,从这篇开始我们看看在rails中怎样进行测试。

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

我们首先测试一下products这个model。代码test/unit目录下的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

然后在命令行里运行测试命令: /rails_apps/depot>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库里已经有我们用到的四个表了。

完成后我们要给products造一些测试数据。我们打开fixtures目录下的products.yml文件,修改里面的内容:

# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.htmlversion_control_book: id:       1 title:     Pragmatic Version Control description:  How to use version control image_url:   http://.../sk_svn_small.jpg price:     29.95 date_available: 2005-01-26 00:00:00automation_book: id:       2 title:     Pragmatic Project Automation description:  How to automate your project image_url:   http://.../sk_auto_small.jpg price:     29.95 date_available: 2004-07-01 00:00:00

在rails里,一个fixture就代表了一个model的初始的内容,这里,我们包含了两个fixture:version_control_book和automation_book。每个fixture的内容都由列名和对应的内容组成,并且由冒号和空格隔开(Tab是不行的)如果在运行测试的时候提示:

Fixture::FormatError: a YAML error occurred parsing………

那么肯定是yml文件的格式问题。

定义好了fixture,怎样使用它呢?回头看看上面的products_test.rb文件,里面有一句:fixtures :products,作为约定,products_test将从products.yml里加载fixture。下面我们再次运行测试命令:

depot>ruby test/unit/product_test.rb

这次正确执行了,屏幕上会显示信息:

Loaded suite test/unit/product_testStarted.Finished in 0.063 seconds.  1 tests, 1 assertions, 0 failures, 0 errors

再回头看数据库里,products表中新插入了两条记录,和我们在products.yml文件中作配置的一样。

而是他们在同伴们都睡着的时候,一步步艰辛地向上攀爬的。

Rubyonrails开发从头来(windows)(十九)-测试开始

相关文章:

你感兴趣的文章:

标签云: