我的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代码没有成功完成会话值分配。
答案 0 :(得分: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