Datasheet
Chapter 1: Building Resources
32
This might seem like overkill, to have a unit test for equality, but it took very little time to put together,
and it makes me less concerned about the bane of the unit tester — the test that really is failing but
incorrectly reports that it passed.
The data for the new ingredients comes in as a raw string via the ingredient text area. It ’ s the
responsibility of the recipe object to convert that string into the actual ingredient objects. Therefore, I
created unit tests in
recipe_test.rb to cover the ingredient - adding functionality. The first test merely
asserts that ingredients in the recipe are always in the order denoted by their
order_of attribute. To
make this test meaningful, the ingredient fixtures are defined in the YAML file out of order, so the test
really does check that the recipe object orders them, as you can see here:
def test_ingredients_should_be_in_order
subject = Recipe.find(1)
assert_equal([1, 2, 3],
subject.ingredients.collect { |i| i.order_of })
end
Making the ingredients display in order is extremely easy. You just add this at the beginning of the
Recipe class recipe.rb file:
has_many :ingredients, :order = > “order_of ASC”,
:dependent = > :destroy
The ingredient.rb file needs a corresponding belongs_to :recipe statement. The :order
argument here is passed directly to the SQL database to order the ingredients when the database is
queried for the related objects.
The test for the ingredient string takes an ingredient string and three expected ingredients, and compares
the resulting ingredient list of the recipe with the expected ingredients. It goes in
recipe_test.rb like this:
def test_ingredient_string_should_set_ingredients
subject = Recipe.find(2)
subject.ingredient_string =
“2 cups carrots, diced\n\n1/2 tablespoon salt\n\n1 1/3 cups stock”
assert_equal(3, subject.ingredients.count)
expected_1 = Ingredient.new(:recipe_id = > 2, :order_of = > 1,
:amount = > 2, :unit = > “cups”, :ingredient = > “carrots”,
:instruction = > “diced”)
expected_2 = Ingredient.new(:recipe_id = > 2, :order_of = > 2,
:amount = > 0.5, :unit = > “tablespoons”, :ingredient = > “salt”,
:instruction = > “”)
expected_3 = Ingredient.new(:recipe_id = > 2, :order_of = > 3,
:amount = > 1.333, :unit = > “cups”, :ingredient = > “stock”,
:instruction = > “”)
assert_equal_ingredient(expected_1, subject.ingredients[0])
assert_equal_ingredient(expected_2, subject.ingredients[1])
assert_equal_ingredient(expected_3, subject.ingredients[2])
end
c01.indd 32c01.indd 32 1/30/08 4:02:30 PM1/30/08 4:02:30 PM