代码之家  ›  专栏  ›  技术社区  ›  ChrisJ

验证用户是否通过操作身份验证

  •  0
  • ChrisJ  · 技术社区  · 8 年前

    我正在使用device,并希望检查我的规范中是否包含某些控制器操作 authenticate_user!

    我看过了设计文档,我觉得有一些非常简单和明显的东西,我不了解设计的工作方式。

    基于 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
    

    库控制器规范.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
    

    控制器本身:

    库_控制器.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
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   ChrisJ    8 年前

    好吧,那太尴尬了。结果我的规范中的期望和方法调用顺序错误。应该是:

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