预期响应为 <:success>,但为 <302> [英] Expected response to be a <:success>, but was <302>

查看:36
本文介绍了预期响应为 <:success>,但为 <302>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm following "Agile web development with rails" book. I have a problem. this is my new method in order controller:

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 命令行检查它如下:

I checked it with rails command line as follows:

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 是空的?

li.cart shows the corresponding cart, but cart.line_items is empty. the two model (carts and line_items) and related to each other. why is the cart.line_items empty?

推荐答案

save 将列表项分配到购物车后.

save your list item after assigning it the cart.

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 代码用于重定向.

Just assigning will not register the change in the database and hence @cart.line_items will remain empty. Thus, in your controller the if check will redirect. 302 code is for redirection.

这篇关于预期响应为 &lt;:success&gt;,但为 &lt;302&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆