Katsuo said:
Hi, I am pretty new to programming.
There is no time like when you are starting to learn unit tests.
Rails comes with one of the best test rigs in the industry, and you should be
writing a case for each branch of this.
What is the good way to write the
following condition.
def cart
if request.post and @cart.size < 10
puts "order accepted"
else
redirect_to :action => 'list'
end
end
Roughly, the first test/functional case would be:
def test_get_cart
get :cart
assert_redirected_to :action => 'list'
end
Now we have to ask where @cart came from. It does not stay "in memory" anywhere
between two hits of a web page. I would link a cart table to the user table (I
would use test/unit to add those features to your Cart and User models first.)
Then I would pass the user_id into the params of the post methods:
def test_post_cart
# code here to put 9 items in user's cart
post :cart, :user_id => user.id
assert_redirected_to :action => 'list'
end
The def cart would then read params[:user_id], fetch the correct user, and then
fetch their current cart.
Over time, these tests will help it remain correct as your upgrade your code.
Run all the tests after every few edits, and add them for every line of code you
add.