【问题标题】:Verify user authenticated for actions验证用户已通过操作身份验证
【发布时间】:2016-06-11 04:02:03
【问题描述】:

我正在使用设计并希望检查我的规范,以确保某些控制器操作已被 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

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

【问题讨论】:

    标签: ruby-on-rails-4 devise rspec-rails


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-07
      • 2014-12-25
      • 1970-01-01
      相关资源
      最近更新 更多