小编enr*_*stn的帖子

使用 RSpec 测试控制器时模拟 CanCan 授权

这是我要测试的控制器:

class UsersController < ApplicationController
  load_and_authorize_resource

  def index
    @users = User.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @users }
    end
  end

  def show
    @user = User.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @user }
    end
  end

  #other actions here

end
Run Code Online (Sandbox Code Playgroud)

如您所见,我使用了 CanCan 方法,load_and_authorize_resource因此我为 RSpec 编写了一个 ControllerHelper:

# spec/support/controller_spec.rb
module ControllerHelper
  def should_authorize(action, subject)
    controller.should_receive(:authorize!).with(action, subject).and_return('passed!')
  end
end
Run Code Online (Sandbox Code Playgroud)

然后我编写了 UserController 规范:

# spec/controllers/users_controller_spec.rb
require 'spec_helper'

describe UsersController do

  describe "GET #index" …
Run Code Online (Sandbox Code Playgroud)

ruby testing rspec ruby-on-rails cancan

5
推荐指数
1
解决办法
4263
查看次数

标签 统计

cancan ×1

rspec ×1

ruby ×1

ruby-on-rails ×1

testing ×1