1. Why write Tests
Rails makes it easy for us to write tests. When we created model and controller, rails helped us create the skeleton code for the test.
By simply running your test code, you can make sure that your code still satisfies the requirements after refactoring.
The rails test simulates the browser request so that you can test the application's response without the browser.
2. Test Introduction
Because every rails application has a lot of interaction with the database, your test needs a database to interact with. To better write tests, you need to know how to build a database and load sample data.
2.1. Three Environmental
There are three environments for each rails application: production, development, testing.
The database settings for these three environments are included in the Config/database.yml file.
If you want to perform data operations in a test database, you need to map the database structure of the development environment to the test environment. You can execute the following command.
Rake Db:test:prepare
2.2. Test folder structure
When you use the rails new command to create an application, rails will help you create a test folder that contains the following contents.
root@web:/home/railsapp/login# ls-f test/
FIXTURES/FUNCTIONAL/INTEGRATION/PERFORMANCE/TEST_HELPER.RB unit/
The Unit folder holds tests for model, the functional folder holds tests for controller, the integration folder holds tests for controller interactions, and the fixtures folder is used to organize test data. TEST_HELPER.RB Save configuration information for the test environment.
The inside of 2.3.Fixtures
A good test, you need to build some test data. In rails, you can implement it by customizing the fixtures.
2.3.1. What is fixtures?
Fixtures allows you to populate the test database with predefined data before the test runs. Fixtures is a database-independent, it is a yaml format.
When you create a new model using the rails G model, a fixtures is automatically created in the fixtures folder.
2.3.2.YAML
Yaml is a very friendly format for describing data. The suffixes of these fixtures are. yml. For example, Users.yml.
# Lo & behold! I am a YAML comment!
David:
name:david heinemeier Hansson
birthday:1979-10-15
profession:systems Development
Steve:
name:steve Ross Kellock
birthday:1974-09-27
Profession:guy with keyboard
2.3.3. Inline Erb
Ruby code can also be embedded in Yml, which is preprocessed before loading the fixtures.
A variable earch_size is defined in the following yml.
<% earth_size =%>
Mercury:
size: <%= earth_size/50%> brightest_on
: <%= 113.days.ago.to_ S (:d b)%>
Venus:
Size: <%= earth_size/2%> brightest_on
: <%= 67.days.ago.to_s (:d b)%>
Mars:
Size: <%= earth_size-69%>
brightest_on: <%= 13.days.from_now.to_s (:d b)%>
The ruby code is contained in the <%%>.