A Guide to Testing Rails Applications
1 Why Write Tests for your Rails Applications?
Rails tests can also simulate browser requests and thus you can test your application’s response without having to test it through your browser.
这是个好的观点,可以触发无限的想象,可拓展性还是相当大的哦!
2 Introduction to Testing
test文件夹下各个模块的作用:
The unit folder is meant to hold tests for your models, the functional folder is meant to hold tests for your controllers, and the integration folder is meant to hold tests that involve any number of controllers interacting. Fixtures are a way of organizing test data; they reside in the fixtures folder. The test_helper.rb file holds the default configuration for your tests.
$ ls
fixtures functional integration performance test_helper.rb unit
少说了一个performance文件夹哦!
The performances directory is used to store performance tests. They’re basically integration tests that run a code profiler on your tests; the results of those tests are outputted to the tmp/performance directory.
2.3 The Low-Down on Fixtures
2.3.1 What are Fixtures?
You’ll find fixtures under your test/fixtures directory. When you run rails generate model to create a new model, fixture stubs will be automatically created and placed in this directory. 再清楚不过了,fixtures sample 文件是与model一一对应的,是在生成model的时候关联生成的。
2.3.2 YAML
2.3.3 ERb’in It Up (in YAML file)
ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures.
2.3.4 Fixtures in Action
初始化的过程:Rails by default automatically loads all fixtures from the test/fixtures folder for your unit and functional test. Loading involves three steps:
- Remove any existing data from the table corresponding to the fixture
- Load the fixture data into the table
- Dump the fixture data into a variable in case you want to access it directly
2.3.5 Hashes with Special Powers
Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case.
Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.
上述涉及两个不同的层面,前者是数据结构(Hash)表的层面,后者是类的层面。
3 Unit Testing your Models
require 'test_helper'
As you know by now, test_helper.rb sp