预期的响应是<:success>,但是< 302>

时间:2012-07-09 08:53:47

标签: ruby-on-rails ruby-on-rails-3

我正在关注“使用rails进行敏捷Web开发”一书。我有个问题。 这是new控制器中的order方法:

def new
  @cart = current_cart
  if @cart.line_items.empty?
    redirect_to store_url, notice: "Your cart is empty"
    return
  end

  @order = Order.new

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @order }
  end
end

这是测试:

test "should get new" do
  cart = Cart.create
  session[:cart_id] = cart.id
  li = LineItem.create(product: products(:ruby))
  li.cart = cart

  get :new
  assert_response :success
end

rake test显示失败:

Expected response to be a <:success>, but was <302>

我用rails命令行检查了它,如下所示:

cart = Cart.create
=> #<Cart id: 24, created_at: "2012-07-09 08:39:36", updated_at: "2012-07-09 08:39:36">

products = Product.create(:title => "Lorem Ipsum", :description => "Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem", :price => 49.50, :image_url => "ruby.png")
=> #<Product id: nil, title: "Lorem Ipsum", description: "Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem", image_url: "ruby.png", price: #<BigDecimal:434f108,'0.495E2',18(45)>, created_at: nil, updated_at: nil>

li = LineItem.create(product: products)
=> #<LineItem id: 106, product_id: nil, cart_id: nil, created_at: "2012-07-09 08:41:29", updated_at: "2012-07-09 08:41:29", quantity: 1, price: nil, order_id: nil>

li.cart = cart
=> #<Cart id: 24, created_at: "2012-07-09 08:39:36", updated_at: "2012-07-09 08:39:36">

li.cart显示相应的cart,但cart.line_items为空。两个模型(carts和line_items)并且彼此相关。为什么cart.line_items为空?

2 个答案:

答案 0 :(得分:2)

分配到购物车后,

save您的列表项。

test "should get new" do
  cart = Cart.create
  session[:cart_id] = cart.id
  li = LineItem.create(product: products(:ruby))
  li.cart = cart

  li.save! // Do this and make sure it doesn't raise an exception.

  get :new
  assert_response :success
end

只是分配不会在数据库中注册更改,因此@cart.line_items将保持为空。因此,在您的控制器中,if检查将重定向。 302代码用于重定向。

答案 1 :(得分:0)

或只使用write_attribute或update_attribute

li.write_attribute :cart, cart