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