if statement with multiple conditions

K

Katsuo Isono

Hi, I am pretty new to programming. 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
 
S

Sebastian Hungerecker

Katsuo said:
Hi, I am pretty new to programming. 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

That's a perfectly reasonable way to write it.
 
P

Phlip

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top