验证用户已通过操作身份验证

Verify user authenticated for actions

我正在使用 devise 并想查看我的规格,确定 authenticate_user!

涵盖了某些控制器操作

我查看了 devise 文档,我觉得有一些非常简单和明显的东西我没有了解 devise 的工作方式。

基于 this SO post 我建立了一个规范来检查这个,但它似乎不起作用。

当我 运行 规范时,我得到:

 Failure/Error: expect(controller).to receive(:authenticate_user!)

   (#<LibrariesController:0x000001035639f8>).authenticate_user!(*(any args))
       expected: 1 time with any arguments
       received: 0 times with any arguments

libraries_controller_spec.rb

require 'rails_helper'

RSpec.describe LibrariesController, type: :controller do

  let(:valid_attributes) {
    skip("Add a hash of attributes valid for your model")
  }

  let(:invalid_attributes) {
    skip("Add a hash of attributes invalid for your model")
  }

  let(:valid_session) { {} }

  describe "GET #index" do
    it "should be authenticated" do
      get :index, {}
      expect(controller).to receive(:authenticate_user!)
    end
  end
end

控制器本身:

libraries_controller.rb

class LibrariesController < ApplicationController
  before_action :set_library, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!

  # GET /libraries
  # GET /libraries.json
  def index
    @libraries = Library.all
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_library
      @library = Library.find(params[:id])
    end
end

嗯,这很尴尬。事实证明,我的规范中的期望和方法调用顺序错误。应该是:

describe "GET #index" do
  it "should be authenticated" do
    expect(controller).to receive(:authenticate_user!)
    get :index, {}
  end
end