Datasheet
Chapter 1: Building Resources
31
“2 cups carrots, diced\n\n1/2 tablespoon salt\n\n1 1/3 cups stock”,
:directions = > “Ask Grandma”}
assert_difference(‘Recipe.count’) do
post :create, :recipe = > recipe_hash
end
expected_recipe = Recipe.new(recipe_hash)
new_recipe = Recipe.find(:all, :order = > “id DESC”, :limit = > 1)[0]
assert_equal(expected_recipe, new_recipe)
assert_equal(3, new_recipe.ingredients.size)
assert_redirected_to recipe_path(assigns(:recipe))
end
In the new test, a hash with potential recipe data is defined, and sent to Rails via the post method. Then
two recipes are compared, one created directly from the hash, and the other retrieved from the database
where Rails put it (finding the recipe with the highest ID). The code then asserts that the two recipes
are equal, and somewhat redundantly asserts that the new recipe has created three ingredients from the
ingredients sent.
For that test to work, you also need to define equality for a recipe based on the values and not on the
object ID. I created the following (rather ugly) unit test for for the
recipe_test.rb file, and then
the actual code for
recipe.rb :
def test_should_be_equal
hash = {:title = > “recipe title”,
:description = > “recipe description”, :servings = > 1,
:directions = > “do it”, }
recipe_expected = Recipe.new(hash)
recipe_should_be_equal = Recipe.new(hash)
assert_equal(recipe_expected, recipe_should_be_equal)
recipe_different_title = Recipe.new(hash)
recipe_different_title.title = “different title”
assert_not_equal(recipe_expected, recipe_different_title)
recipe_different_dirs = Recipe.new(hash)
recipe_different_dirs.directions = “different directions”
assert_not_equal(recipe_expected, recipe_different_dirs)
recipe_different_description = Recipe.new(hash)
recipe_different_description.description = “different description”
assert_not_equal(recipe_expected, recipe_different_description)
recipe_different_servings = Recipe.new(hash)
recipe_different_servings.servings = “more than one”
assert_not_equal(recipe_expected, recipe_different_servings)
end
def ==(other)
self.title == other.title & &
self.servings == other.servings & &
self.description == other.description & &
self.directions == other.directions
end
c01.indd 31c01.indd 31 1/30/08 4:02:30 PM1/30/08 4:02:30 PM