Recipe 7.23. Improving Feedback by Running Tests Continuously


Problem

Contributed by: Joe Van Dyk

You would like to run your tests more often, but you find it cumbersome to remember to run the tests after every file save.

Solution

Eric Hodel's autotest program allows you to run your tests continually in the background. It constantly scans your Rails application for changes, and upon noticing a change, runs the tests that are affected by that file change. autotest is a part of ZenTest. To install it, run:

$ sudo gem install zentest             

To run autotest, go to $RAILS_ROOT, and run the autotest command:

$ autotest -rails /usr/local/bin/ruby -I.:lib:test -rtest/unit -e "%w[test/functional/foo_controller_test.rb test/unit/foo_test.rb].each { |f| load f }" | unit_diff -u Loaded suite -e Started .. Finished in 0.027919 seconds. 2 tests, 2 assertions, 0 failures, 0 errors

autotest runs in the background, waiting like a silent ninja for you to make a change to a file. Upon saving the file, autotest automatically runs all the tests that are related to that file. Here's the result of making a change to a file that resulted in a failed test:

/usr/local/bin/ruby -I.:lib:test -rtest/unit -e "%w[test/unit/foo_test.rb].each { |f| load f }" | unit_diff -u Loaded suite -e Started F Finished in 0.167108 seconds. 1) Failure: test_truth(FooTest) [./test/unit/foo_test.rb:8]: <false> is not true. 1 tests, 1 assertions, 1 failures, 0 errors

Fixing the test gives you:

/usr/local/bin/ruby -I.:lib:test test/unit/foo_test.rb -n "/^(test_truth)$/" | unit_diff -u Loaded suite test/unit/foo_test Started . Finished in 0.033695 seconds. 1 tests, 1 assertions, 0 failures, 0 errors /usr/local/bin/ruby -I.:lib:test -rtest/unit -e "%w[test/functional/foo_controller_test.rb test/unit/foo_test.rb].each { |f| load f }" | unit_diff -u Loaded suite -e Started .. Finished in 0.029824 seconds. 2 tests, 2 assertions, 0 failures, 0 errors

Discussion

Automated tests can be lifesavers in any nontrivial project. autotest allows you to safely and quickly refactor your code without having to remember to run your tests. If you change the database structure through a migration, you must kill autotest (done by pressing Ctrl-C twice) and restart it. That allows autotest to reload its test database.

See Also

  • ZenTest includes other helpful libraries that make testing your applications easier. You can find out more about these tools at http://www.zenspider.com/ZSS/Products/ZenTest.




Rails Cookbook
Rails Cookbook (Cookbooks (OReilly))
ISBN: 0596527314
EAN: 2147483647
Year: 2007
Pages: 250
Authors: Rob Orsini

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net