0

我的rails代码如下:

class MyController < ApplicationController
  def index
    @session_is_admin = session[:user_permission][:is_admin]
    begin
      @obj = Class.all
      respond_to do |format|
        format.html # index.html.erb
      end
    rescue
    end
  end
end

Rspec 代码:在 (rspec/controllers) 下

require 'spec_helper'

describe MyController do
  describe "GET index" do
    it "populates an array of data" do
       get :index
       session[:user_permission][:is_admin] = false
       assigns(:session_is_admin).should eq(false)
    end
  end
end

执行后它向我提供以下错误:

 1) MyController GET index populates an array of data
     Failure/Error: get :index
     NoMethodError:
       undefined method `[]' for nil:NilClass
     # ./app/controllers/my_controller.rb:16:in `index'
     # ./spec/controllers/my_controller_spec.rb:20:in `block (3 levels) in <top (required)>'

Finished in 9.27 seconds
1 example, 1 failure

请帮我解决上述问题。这是由于我的 rspec 代码未成功完成会话值分配。

4

1 回答 1

1

您可能需要在调用控制器操作之前设置会话值。此外,您的会话设置仅在session[:user_permission]已经是Hash.

请尝试以下操作:

it "populates an array of data" do
  session[:user_permission] = {:is_admin => false}
  get :index
  assigns(:session_is_admin).should eq(false)
end
于 2013-10-16T07:14:28.837 回答