简体   繁体   中英

How to test subdomain constraint with RSpec & Rails 4

I'm trying to write a controller test which tests a subdomain constraint. However, I'm unable to get RSpec to set the subdomain and return an error if the subdomain isn't accurate.

I'm using Rails 4.2.6 and RSpec ~3.4

routes.rb

namespace :frontend_api do
  constraints subdomain: 'frontend-api' do
    resources :events, only: [:index]
  end
end

events_controller.rb

module FrontendAPI
  class EventsController < FrontendAPI::BaseController
    def index
      render json: []
    end
  end
end

spec

RSpec.describe FrontendAPI::EventsController do
  describe 'GET #index' do
    context 'wrong subdomain' do
      before do
        @request.host = 'foo.example.com'
      end

      it 'responds with 404' do
        get :index
        expect(response).to have_http_status(:not_found)
      end
    end
  end
end

Is there some other way of doing this?

You can accomplish this by using the full URL in your tests instead of setting the host in a before block.

Try:

RSpec.describe FrontendAPI::EventsController do
  describe 'GET #index' do
    let(:url) { 'http://subdomain.example.com' }
    let(:bad_url) { 'http://foo.example.com' }

    context 'wrong subdomain' do        
      it 'responds with 404' do
        get "#{bad_url}/route"
        expect(response).to have_http_status(:not_found)
      end
    end
  end
end

There is a similar question and answer here testing routes with subdomain constraints using rspec

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM