In the practice of agile development, the test drive is indispensable. This article looks at a test-driven development example in rails.
Before we wrote and conducted some unit tests and functional tests, our customers suddenly asked to add a feature: Each user of the system could query the product.
We first sketched some sketches to sort out our ideas and designs, and then we started writing code. We already have a general idea of what to do, but if there is more feedback it will help us get on the right path. We'll write the test code before we dive into the code. Consider how our code will work, identify some protocols, and when the test passes, your code will be OK.
Now, let's consider the query function test, which controller to control the query operation? Users and administrators can query, we can add a search () action in store_controller.rb or ADMIN_CONTROLLER.RB, but here we add a searchcontroller, and contains a method search. To execute a command on the Rails command line:
Depot>ruby script/generate Controller Search Search
We see that the corresponding files have been generated under the App/controllers and test/functional directories. But now we don't care about the implementation of the Searchcontroller search method, we care about the results we expect to see when we test. Now add the test code and add the Test_search method to the TEST/FUNCTIONAL/SEARCH_CONTROLLER_TEST.RB:
The first thing we thought of was calling the action of search, and then deciding if it was responding:
Get:search,: Title => "Pragmatic Version control"
assert_response:success
According to the previous sketch, we should display a flash message on the page, so we want to determine the text of the flash information and whether the correct page is displayed:
Assert_equal "Found 1 product (s).", Flash[:notice]
assert_template "Search/results"
Then we want to judge the product information obtained by the query:
Products = assigns (:p roducts)
Assert_not_nil products
assert_equal 1, products.size
assert_equal " Pragmatic Version Control ", Products[0].title
We also want to determine some of the content of the page used to display the results of the query, the items we have queried are displayed on the page as a list, and we use the same CSS style as the Catelog view:
Assert_tag:tag => "Div",
: Attributes => {: Class => "Results"},
: Children => {: Count => 1,
: Only => {: Tag => ' div ',
: Attributes => {: Class => ' Catalogentry '}}}