代码之家  ›  专栏  ›  技术社区  ›  Daniel Viglione

控制器测试以捕获未经授权的响应

  •  -1
  • Daniel Viglione  · 技术社区  · 6 年前

    我使用Rspec来测试控制器的行为。当用户访问未经授权的页面时,他们将重定向到根url并传递消息“you are authorized”(您未经授权),如my cancan(gem)rescue block中所指定:

    rescue_from CanCan::AccessDenied do |exception|
      redirect_to root_url, alert: exception.message
    end
    

    但是,测试失败:

    expected: "http://test.host/"
    got: "http://test.host/users/sign_in"
    

    另一个失败:

    expected "<html><body>You are being <a href=\"http://test.host/users/sign_in\">redirected</a>.</body></html>" to include "You are not authorized to access this page."
    

    这些是规格:

    require 'rails_helper'
    
    describe CodesController, type: :controller do
      login_user
    
      describe "Get index" do
        it 'denies access to marketing user' do
          get :index
          expect(response.status).to be == 302
        end
    
        it 'redirects user to home page' do
          get :index
          expect(response.location).to eq(root_url)
        end
    
        it 'alerts user of unauthorized access' do
          get :index
          expect(response.body).to include('You are not authorized to access this page.')
        end
      end
    end
    

    这是登录用户的来源:

    module ControllerMacros
      def login_user
        before :example do
          @request.env["devise.mapping"] = Devise.mappings[:user]
          marketing = create :marketing
          sign_in marketing
        end
      end
    end
    

    config.extend ControllerMacros, type: :controller
    

    我正在使用:

    rspec-rails 3.8.0  
    devise 4.5.0
    rails 4.2.10
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   lacostenycoder    6 年前

    更新:您不需要第三个测试,因为这是视图逻辑而不是控制器,而且警报应该在rails中按预期工作。不过,你只需要测试一下你是否按预期被重定向了。试试这个:

    require 'rails_helper'
    
    describe CodesController, type: :controller do
      login_user
    
      describe "Get index" do
        subject { get :index }  
    
        it 'denies access to marketing user' do
          subject
          expect(response.status).to be == 302
        end
    
        it 'redirects user to home page' do
          expect(subject).to redirect_to(root_url)
        end
    
      end
    end
    
    推荐文章