Continuing our series on setting up an online bookstore with Ruby-on-Rails, this two-part tutorial explains how to implement the shopping cart. It is excerpted from chapter five of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Shopping Cart Implementation - Setting Up the Shopping Cart (Page 2 of 4 )
Once again, we start our sprint by creating a test case for adding an item to the shopping cart. This time, we will use the Rails functional tests. We could use integration tests, but since we are testing the functionality of a single controller (which we will create first) in this case, we agree to use functional tests for this sprint.
Creating the Controller
Our first step is to use the script/generatecommand to create the newCartcontroller, as follows:
$ script/generate controller Cart
Creating a new controller for our shopping cart also provides us with a stub file for the functional tests.
Adding a Functional Test
Open test/functional/cart_controller_test.rband replace the dummytest_truthmethod with the following test case:
def test_adding assert_difference(CartItem, :count) do post :add, :id => 4 end
assert_response :redirect assert_redirected_to :controller => "catalog" assert_equal 1, Cart.find(@request.session[:cart_id]).cart_items.size end
In this test, we first check that posting a form to theaddaction actually creates a newCartItem. Then we check that after the form post, we are redirected to the catalog controller and that the current shopping cart is populated with an item.
If you canít figure out whatís happening here, donít worry. Once we start implementing the shopping cart, it will be clear how the test works.