0

我正在尝试在控制器中测试我的#new 视图

class ApplicationController < ActionController::Base
  before_action :current_cart
  protect_from_forgery with: :exception

  private
    def current_cart
        @cart = Cart.find(session[:cart_id])
    rescue ActiveRecord::RecordNotFound
      @cart = Cart.create
      session[:cart_id] = @cart.id  
      @cart
    end 
end


class controller < ApplicationController
  def new
    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
      format.xml { render :xml => @order }
    end  
  end

规格:

  describe "GET #new" do
    it "renders the :new template" do
      product = FactoryGirl.create(:product)
      @cart.add_product(product.id)
      get :new 
      response.should render_template :new
    end
  end 

@cart没有定义??

任何线索,谢谢

4

1 回答 1

0

您无需在测试中检查或添加到 @cart。您不是在测试购物车的保存,而是在测试您的新购物车是否会呈现。如果你把它拿出来,它就会过去。此外,最好不要挽救这样的异常。你可以做一个@cart ||= Cart.find_or_create_by_id(session[:cart_id])方法

编辑:我错过了那个重定向。

describe "GET #new" do    
  let(:cart)    { FactoryGirl.create(:cart) }
  let(:product) { FactoryGirl.create(:product) }

  it "renders the :new template" do
    cart.add_product(product.id)
    session[:cart_id] = cart.id
    get :new
    response.should render_template :new
  end
end 
于 2013-11-06T21:30:41.633 回答