I’m making my way through Agile Web Development with Rails TDD style after an earlier sillier attempt at waiting until the testing chapter about 150 pages into the book. I really like the skeletons for unit tests and functional tests. Then I wanted to test the following helper method in the ApplicationHelper class:
def fmt_dollars(amount) sprintf("$%0.2f", amount) end
This resulted in a bit of thrashing for about 30 minutes without much luck until I came across a post by Doug Alcorn on Testing Rails Helpers. The solution looks like:
require File.dirname(__FILE__) + '/../test_helper'
class ApplicationHelperTest < Test::Unit::TestCase include ActionView::Helpers::TextHelper include ActionView::Helpers::TagHelper include ApplicationHelper # include whatever helpers you want to test here, sometimes you'll need # to include some of the Rails helpers, as I've done above.
def test_formatting_dollars assert_equal "$29.90", fmt_dollars(29.9) end end
Considering unit testing utility classes are some of the easiest things to test in Java I felt a bit incompetent when I had a tough time with this. I think I need to better understand how Ruby does packaging with modules and how the include keyword really works.