Rspec每秒获取另一个端点-ActionController :: UrlGenerationError

在我的Grape / Rails应用程序中,我已经在ApplicationController中实施了维护模式,因此当该模式处于活动状态时,它将从应用程序中的任何位置重定向到maintenance_mode_path。如何强制rspec在一段时间内处于不同的端点。 api/v1/new_endpoint,而整个测试都在MaintenanceModeController中进行?

maintenance_mode_controller_spec

context 'when maintenance mode is active' do

  context 'when current page is not maintenance page' do
    let(:call_endpoint) { get('/api/v1/new_endpoint') }

    it 'redirect to the maintenance page' do
      call_endpoint
      expect(response).to have_http_status(:redirect)
    end
  end
end

但是上面的代码有一个错误

  

失败/错误:let(:call_endpoint){get('/ api / v1 / bank_partners')}

     

actionController :: UrlGenerationError:没有路由匹配{:action =>“ / api / v1 / new_endpoint”,:controller =>“ maintenance_mode”}

chaomi87 回答:Rspec每秒获取另一个端点-ActionController :: UrlGenerationError

您完全无法使用控制器规格对此进行测试。控制器规范会创建一个带有模拟请求的控制器实例,然后在其上运行测试。例如,当您在控制器测试中调用get :show时,您实际上是在模拟的控制器上调用#show方法。 由于它实际上并未创建HTTP请求,因此它无法与系统中的其他控制器进行实际交互。

改为使用request spec

# /spec/requests/maintainence_mode_spec.rb
require "rails_helper"

RSpec.describe "Maintenance mode",type: :request do
  context 'when maintenance mode is active' do
    context 'when current page is not maintenance page' do
      let(:call_endpoint) { get('/api/v1/new_endpoint') }
      it 'redirects to the maintenance page' do
        call_endpoint
        expect(response).to redirect_to('/somewhere')
      end
    end
  end
end
  

请求规范提供了控制器规范的高级替代方案。在   实际上,从RSpec 3.5开始,Rails和RSpec团队都不鼓励   直接测试控制器以支持诸如请求之类的功能测试   规格。

本文链接:https://www.f2er.com/3074234.html

大家都在问