如何使用 RSpec 和 Rails 4 测试子域名约束

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

还有其他的方法吗?

1个回答

3

您可以通过在测试中使用完整的URL而不是在before块中设置主机来实现此目标。

尝试:

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测试具有子域约束的路由


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接