Rails testing: session mechanism creates new cart instead of using fixture
I am new to Rails and am following the 'Agile Web Devel开发者_开发技巧opment with Rails' book. Currently I am testing my cart and line items.
In my fixtures I have 2 line items. I delete one in the test, so one more remains in the cart. However I think due to my session mechanism the controller now uses a new empty cart instead of the fixture cart. This caused my test to fail.
In my *application_controller.rb*
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
en
In my *line_items_controller.rb* I have:
def destroy @line_item = LineItem.find(params[:id]) @line_item.destroy
respond_to do |format|
if current_cart.line_items.empty?
format.html { redirect_to(store_url, :notice => 'Your cart is empty') }
else
format.html { redirect_to(current_cart, :notice => 'Item removed' )}
end
format.xml { head :ok }
end
end
And in my *functional\line_items_controller_test.rb* I have:
test "should destroy line_item" do
assert_difference('LineItem.count', -1) do
delete :destroy, :id => @line_item.to_param
end
assert(!@cart.line_items.empty?,'Cart should not be empty')
if @cart.line_items.empty?
assert_redirected_to store_url #this was the redirection result
else
assert_redirected_to cart_path(@cart.id) #but should be this redirection
end
end
The code works in real environment, just that the test fails.
How can I modify my test & code, so fixture-cart and my session mechanism can work together and pass the test?
The controller action takes a second hash of session
variables to use for the request.
delete :destroy, { :id => @line_item.to_param }, { :cart_id => @cart.id }
精彩评论