rspec为会话分配失败

时间:2012-10-11 20:19:34

标签: rspec

我的测试失败并在测试报告中说明

  

失败/错误:分配(:items).should eq(item)expected:[#Item id:   756,product_name:“Item 1”,product_price:310.25,product_balance:   3,active:1,created_at:“2012-10-11 20:10:23”,updated_at:   “2012-10-11 20:10:23”]               得到:[]

请告诉我测试失败的原因是什么?

cart_controller.rb文件

class CartController < ApplicationController
  def index
    @cart = session[:cart] || {}

    @items = Item.where( id: @cart.keys )

    @cart_cost = 0
    @items.each do | item |
      @cart_cost += @cart[ item.id.to_s ]*item.product_price
    end
  end
end

cart_controller_spec.rb

describe CartController do
  context "when user is logged in" do

    before (:each) do
      v = Visitor.create! :username => 'John Doe', :password => '123456'
      session[:logged_in] = 'logged_in'

      session[:cart] = {}
      @cart = session[:cart]

      @normal_item = Item.create! :product_name => 'Item 1',
:product_price => '310.25', :product_balance => '3', :active => '1'
    end

    describe "GET 'index'" do
      it "assigns session cart variable as @cart" do
        get :index
        @cart[ @normal_item.id ] = 1

        assigns(:cart).should eq(session[:cart])

        item = Item.where( id: @cart.keys )
        assigns(:items).should eq(item)
      end
    end

  end

end

1 个答案:

答案 0 :(得分:0)

尝试将会话值作为第二个参数传递给:get,例如:

get :index, {}, { :cart => {}, :logged_in => 'logged_in' }

A Guide To Testing Rails Applications

中有更详细的描述