Datasheet

Chapter 1: Building Resources
26
The test cases I started with are described in the following table.
Case Description
2 cups carrots, diced The basic input structure
2 cups carrots Basic input, minus the instructions
1 carrots, diced Basic input, minus the unit
1 cup carrots Singular unit
2.5 carrots, diced A test to see whether decimal numbers are correctly handled
1/2 carrots, diced A test to see that fractions are handled
1 1/2 carrots, diced A test to see whether improper fractions are handled
Here s what the first two test cases look like in code (again, in test/unit/ingredient_test.rb ):
def test_should_parse_basically
assert_parse(“2 cups carrots, diced”, nil, :recipe_id = > 1, :order_of = > 1,
:amount = > 2, :unit = > “cups”, :ingredient = > “carrots”,
:instruction = > “diced”)
end
def test_should_parse_without_instructions
assert_parse(“2 cups carrots”, nil, :recipe_id = > 1, :order_of = > 1,
:amount = > 2, :unit = > “cups”, :ingredient = > “carrots”,
:instruction = > “”)
end
These test cases use the assert_parse method defined earlier to associate the test string with the
expected features of the resulting ingredient. You should be able to define the remaining tests similarly.
There are, of course, other useful test cases that would make this more robust. Tests for proper error
handling in deliberately odd conditions would also be nice. For right now, though, the previous test
cases provide a sufficient level of complexity to serve as examples of how to do moderately complex
processing on user data.
The way this worked in practice was that I wrote one test, made it work, and then refactored and
simplified the code. I wrote the second test, which failed, and then fixed the code with another round of
refactoring and code cleanup. By the time I finished the last test, the code was in pretty good shape.
Here s a description of the code after that test.
I created a separate class for this called
IngredientParser , and placed the code in a new file, /app/
models/ingredient_parser.rb
. The class starts like this:
class IngredientParser
UNITS = %w{cups pounds ounces tablespoons teaspoons cans cloves}
c01.indd 26c01.indd 26 1/30/08 4:02:28 PM1/30/08 4:02:28 PM