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

2024-05-06

我正在尝试编写一个测试子域约束的​​控制器测试。但是,我无法让 RSpec 设置子域,并且如果子域不准确则返回错误。

我正在使用 Rails 4.2.6 和 RSpec ~3.4

路线.rb

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

事件控制器.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

还有其他方法可以做到这一点吗?


您可以通过在测试中使用完整的 URL 而不是在 before 块中设置主机来完成此操作。

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

这里有一个类似的问题和答案使用 rspec 测试具有子域约束的​​路由 https://stackoverflow.com/questions/9329669/testing-routes-with-subdomain-constraints-using-rspec

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 RSpec & Rails 4 测试子域约束 的相关文章

随机推荐