2

In my Grape/Rails app I've implement maintenance mode in ApplicationController so when this mode is active it will redirect to the maintenance_mode_path from anywhere in the app. How to force rspec to be in a different endpoint for a while eg. api/v1/new_endpoint while the whole test takes place in the 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

But with code above I've got an error

Failure/Error: let(:call_endpoint) { get('/api/v1/bank_partners') }

ActionController::UrlGenerationError: No route matches {:action=>"/api/v1/new_endpoint", :controller=>"maintenance_mode"}

Community
  • 1
  • 1
mr_muscle
  • 2,536
  • 18
  • 61

1 Answers1

2

You can't really test this at all with a controller spec. Controller specs create a instance of a controller with a mocked request which you then run tests on. When you call for example get :show in a controller test you are actually calling the #show method on your mocked controller. Since it does not actually create a HTTP request so there is no way for it to actually interact with the other controllers in the system.

Use a request spec instead:

# /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

Request specs provide a high-level alternative to controller specs. In fact, as of RSpec 3.5, both the Rails and RSpec teams discourage directly testing controllers in favor of functional tests like request specs.

max
  • 96,212
  • 14
  • 104
  • 165