Rails Note #11: TDD and Loading Development Fixtures for Testing
Here is a brief outline on how I am doing test driven development personally.
- Code up tests/functional/foo_controller_test.rb until you know what you expect from the method. Make the test method as self explanatory as much as possible.
def test_goto_restaurant_next end |
- Imagine how the URL parameters will be passed to the controller.
get :goto, 'WHOISD-ABONENT'=> MOBILE_NUMBER, :categ_id => '123', :node_id => '10', :page => '2' |
- At this point. It gets too exciting to code up the controller itself. Hold on, try to make an assertion on a variable that we will use in the view.
assert_equal assigns("sub_menus").length, 2 |
-
Code the controller
-
Code the view
-
Test from the browser.
-
Refactor the testcase and make more assertions.
-
Run the testcase
Now, it could be very hard to execute the tests if you don’t have the same development data inside your testing database. I found a good tip from the Rail’s Way book, and used ar_fixtures.
For whatever reason, dumping data to fixtures is not a part of core Rails. Considering that Rails gives you a to_yaml method on ActiveRecord models and Hash objects, it wouldn’t be too hard to write your own Rake task. However, it’s not necessary to do so because of a well-proven plugin written by Geoff Grosenbach. It’s called ar_fixtures and you can install it with the following command:
$ script/plugin install http://topfunky.net/svn/plugins/ar_fixtures |
Once the plugin is installed, dumping a fixture is a simple matter of invoking a new rake task called rake db:fixtures:dump. Unlike the built-in loading rake task, this one takes a MODEL parameter with the name of the ActiveRecord class that you want to dump data for:
$ rake db:fixtures:dump MODEL=BillingCode |