簡體   English   中英

如何使用RSpec和Rails 4測試子域約束

[英]How to test subdomain constraint with RSpec & Rails 4

我正在嘗試編寫一個測試子域約束的​​控制器測試。 但是,如果子域不准確,我無法讓RSpec設置子域並返回錯誤。

我正在使用Rails 4.2.6和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

規范

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

還有其他方法嗎?

您可以通過在測試中使用完整URL而不是在之前的塊中設置主機來實現此目的。

嘗試:

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

這里有類似的問題和答案,使用rspec測試具有子域約束的​​路由

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM