加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何使用RSpec和Rails 4测试子域约束

发布时间:2020-12-17 02:25:53 所属栏目:百科 来源:网络整理
导读:我正在尝试编写一个测试子域约束的??控制器测试.但是,如果子域不准确,我无法让RSpec设置子域并返回错误. 我正在使用Rails 4.2.6和RSpec~3.4 的routes.rb namespace :frontend_api do constraints subdomain: 'frontend-api' do resources :events,only: [:in
我正在尝试编写一个测试子域约束的??控制器测试.但是,如果子域不准确,我无法让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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读