Saturday, January 15, 2011

Rails - Iteration E1 - recovery from new defect introduced

Interesting, at end of last class all of my tests passed, but today I test my app and find that I have a critical defect!

Post /lines_items?product_id=4 fails horribly when trying to show the cart page with updated list.
Cart page complains about no 'title' attribute for a nil object
/line_items shows that my cart now has a line item for a product id 123456 <- which of course doesn't exist.

Old instincts: well time to add a check for null products and skip processing anything won't work.
New TDD instincts: Whoa! how can all my tests be passing? Why is the product id changing on add_product?

Step 1: Recreate the defect in a test.
Looks like my line_items_controller_test only confirms line item addition and redirect to cart page. But defect manifest at cart page....
Decided to try my hand at 'integration' test, since now testing flow from one controller to another.
> rails generate integration_test user_cart_session_test

Then add test method to the resulting skeleton:

test "line item adds to cart" do
item = products(:ruby)
post "/line_items", :product_id => item.id
follow_redirect!
assert_response :success
end

> rake test:integration --> Same problem as reported in the app!

Last Step: Rollback to a clean branch of code and start lesson over.

> git commit -a -m "test for my broken code"
> git checkout master
> rake test --> lots of problems? Wait the DB was mucked with
> rake db:drop
> rake db:migrate
> rake test --> ah! that's better!
> git checkout class.chapter10 test/integration/ --> pull over my new fangled test
rails test --> look now it's passing, got rid of my bug!
git add test/integration/
git commit -m "adding a functional test for cart and line items"

Note To Self: never ever forget to branch when starting new development! Love this cycle
1) break code unexpectedly
2) build test to reproduce break
3) revert code, import test and start dev over again (and always have access to previous work!)

No comments:

Post a Comment