minitest - 应该使用子域的路由匹配器

标签 minitest shoulda

我正在使用 shoulda 匹配器在新应用程序上使用 Ruby 2.2.0 测试 Rails 4.2.1 上的关键路由。我刚刚将 API 命名空间移至子域,但我不知道如何让 shoulda 路由匹配器(或任何其他简洁的路由测试)正常工作。

这里是一些示例代码:

config/routes.rb(使用 versionist 进行版本控制,但这不应该相关)

  namespace :api, path: '', constraints: { subdomain: 'api'} do
    api_version(module: 'V1',
                path: {value: 'v1'},
                defaults: {format: 'json'}, default: true) do
      resources :bills,         only: :index
    end
  end

app/controllers/api/v1/bills_controller.rb

module API
  module V1
    class Bill < APIVersionsController
      # GET api.example.com/v1/bills.json
      def index
        @bills = Bill.all.limit(10)
        render json: @bills
      end
    end
  end
end

test/controllers/api/v1/routing_test.rb

module API
  module V1
    class RoutingTest < ActionController::TestCase
      setup { @request.host = 'http://api.example.com' }
      should route('/v1/bills')
             .to(controller: :bill, action: :index, format: :json)
    end
  end
end 

在我使用子域之前,应该在我的 BillsControllerTest 中路由('/api/v1/bills').to(action: :index, format: :json) 工作得很好。

现在,当我运行rake test时,我得到Minitest::Assertion: No Route matches "/v1/bills"

  • 我尝试将其放入 BillControllerTest(没有变化);
  • 我尝试过集成测试(路由匹配器不起作用);
  • 我尝试使用 setup { host! 设置主机! 'api.example.com' }setup { @request.host = 'api.example.com' }
  • 我尝试将完整的 URL 放入 get 请求中 ( { get 'http://api.example.com/v1/bills' } );
  • 我尝试将 subdomain: 'api'constraints: subdomain: 'api' 放在任何可能有意义的地方。

使用子域进行路由测试的简洁方法是什么/当前的最佳实践是什么?有没有办法让 shoulda 路由匹配器与它们一起工作?

最佳答案

这最终是一个简单的修复。我只需要在 #to 方法中添加子域约束并确保 #route 方法具有完整的 url:

module API
  module V1
    class RoutingTest < ActionController::TestCase
      should route(:get, 'http://api.example.com/v1')
               .to('api/v1/data#index', 
                   subdomain: 'api', 
                   format: :json)
      ...

或者,如果您在 data_controller_test.rb 中,

module API
  module V1
    class DataControllerTest < ActionController::TestCase
      should route(:get, 'http://api.example.com/v1')
               .to(action: :index, 
                   subdomain: 'api', 
                   format: :json)
      ...

关于minitest - 应该使用子域的路由匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30003374/

相关文章:

ruby-on-rails - BDD on Rails - 社区更支持 Shoulda 还是 RSpec?

ruby-on-rails - 黑白 minitest-rails 和 minitest-spec-rails 有什么区别?

ruby-on-rails - Minitest 5 - 套件级设置

ruby - Guard 不向 growl 发送 gntp 通知

ruby-on-rails - 应该使用自定义关系名称匹配器 has_many

ruby-on-rails - Rails 和 Rspec - 具有一通多态性

ruby-on-rails - Rails 4.2.2-Windows 7/: bundle exec guard 的 git Bash 上未显示测试结果

ruby-on-rails - 运行基本测试时遇到问题(未知属性错误)

ruby-on-rails - 如何有选择地使Rails 3弃用警告静音?

ruby-on-rails - rails/rspec 看不到 shoulda 匹配器