我是 Rails 的新手,正在阅读“使用 Rails 进行敏捷 Web 开发”一书。目前我正在测试我的购物车和订单项。
在我的固定装置中,我有 2 个订单项。我在测试中删除了一个,所以购物车中还剩下一个。 但是我认为由于我的 session 机制, Controller 现在使用一个新的空车而不是夹具车。这导致我的测试失败。
在我的 *application_controller.rb* 中
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
en
在我的 *line_items_controller.rb* 我有:
定义销毁 @line_item = LineItem.find(参数[: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
结束
在我的 *functional\line_items_controller_test.rb* 中我有:
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
该代码在真实环境中工作,只是测试失败。
如何修改我的测试和代码,以便 fixture-cart 和我的 session 机制可以协同工作并通过测试?
最佳答案
Controller Action takes a second hash用于请求的 session
变量。
delete :destroy, { :id => @line_item.to_param }, { :cart_id => @cart.id }
关于ruby-on-rails-3 - 轨道测试 : session mechanism creates new cart instead of using fixture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6659368/