使用应用程序控制器中的实例变量测试控

时间:2013-11-06 21:02:55

标签: ruby-on-rails ruby rspec

我正在尝试在控制器中测试我的#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未定义?

任何线索,谢谢

1 个答案:

答案 0 :(得分: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