我正在使用RSpec(Rails 3.2.8上的2.12)测试视图.我正在使用CanCan有条件地在页面上显示某些元素.这需要一个控制器方法'current_user'.在我的一些规范中,我已经能够存根current_user,例如.controller.stub(:current_user).and_return(etc)或view.stub.etc.
这适用于我的一些规格.但我有一对夫妇在哪里工作,我不明白为什么.
它不工作的两个规范测试一个视图,它调用一个部分,在部分内部我访问'current_user'作为一个方法.错误是
undefined local variable or method `current_user'
Run Code Online (Sandbox Code Playgroud)
所以我想我的问题是如何正确地存根方法,以便可以在局部内部访问它们.
应该怎么做?
我在我的控制器规范中使用了这个:
controller.class.skip_before_action
Run Code Online (Sandbox Code Playgroud)
具体来说,在这种情况下:
controller.class.skip_before_action:require_authorisation_to_view_materials
MaterialsController:
class MaterialsController < ApplicationController
before_action :set_material, only: [:show, :edit, :update, :destroy]
before_action :require_authorisation_to_view_materials, only: [:index, :show]
def require_authorisation_to_view_materials # For Materials Page
unless user_signed_in? && current_user.can_view_materials?
redirect_to root_path, alert: "You are not authorised to view the Materials page."
end
end
# GET /materials
# GET /materials.json
def index
@materials = Material.all
end
# GET /materials/1
# GET /materials/1.json
def show
end
# GET /materials/new
def new
@material = Material.new
end
# GET /materials/1/edit
def edit …Run Code Online (Sandbox Code Playgroud)