I’m following the book Agile web development with Rails 5.1 and I got stuck integrating my test cases with an exercise proposed in the “Play time” section. We are building a online store that has a cart
the cart has_many line_items
, so far so good, one of the exercises was prevent someone from accessing any cart but the one on their session, easy enough (I thought) and created the following validation:
def show
invalid_cart if @cart.id != session[:cart_id]
end
private
def invalid_cart
logger.error "Attempt ot access invalid cart #{params[:id]}"
redirect_to store_index_url, notice: 'Invalid cart'
end
Well that works on the browser but that broke my tests for example, I had:
setup do
@cart = carts(:one)
end
...
test "should show cart" do
get cart_url @cart
assert_response :success
end
It fails because it is not a response 200 it a response 300 for the redirect I did when the session[:cart_id] was not the same (inside the invalid_cart method), I tried something like:
test "should show cart" do
get cart_url @cart, params: { session: { cart_id: @cart.id } }
assert_response :success
end
but this seems to be frown upon (’https://github.com/rails/rails/issues/23386#issuecomment-178013357').
So I’m a little bit lost here. how should the verification for a valid cart be normally implemented? and still have meaningful tests.
thanks your for time
To recap: set request.session[:cart_id]
in the assembly phase of your test case.