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

时间:2016-06-29 20:21:15

标签: ruby-on-rails rspec

我正在尝试编写一个测试子域约束的​​控制器测试。但是,如果子域不准确,我无法让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 个答案:

答案 0 :(得分:3)

您可以通过在测试中使用完整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

这里有一个类似的问题和答案testing routes with subdomain constraints using rspec