如何识别 RSpec 控制器规范中调用的路由

How to identify the route being called in a RSpec controller spec

我有一个 RSpec 控制器规范,我正在尝试了解如何找到在我的示例中调用的确切路线。

在services_controller_spec.rb中:

describe 'create comment' do
  let!(:service) { FactoryGirl.create(:service) }

  describe 'with valid comment' do
    it 'creates a new comment' do
      expect {
        post :add_comment, id: service.id
      }.to change(service.service_comments, :count).by(1)

      expect(response).to redirect_to(service_path(service))
    end
  end
end

有没有办法 ppputs 通过 post 发送的路由?

我问是因为我想 post 到路线 /services/:id/add_comment 并想验证路线的确切去向。

这条路线我的routes.rb:

resources :services do
  member do
     post 'add_comment'
  end
end

您可以打印 rspec-rails 控制器规范中使用的路由名称,如下所示:

routes.formatter.send(
  :match_route,
  nil,
  controller: ServicesController.controller_path,
  action: 'add_comment', # what you passed to the get method, but a string, not a symbol
  id: service.id         # the other options that you passed to the get method
) { |route| puts route.name }

rspec-rails 仅在内部使用路由。上面是rspec-rails(实际上是ActionController::TestCase,rspec-rails使用)如何查找和使用路由,但是有一个块只是打印路线。

在规范中的 post 调用和上面的调用之间有很多方法调用,所以如果你想了解 rspec-rails 是如何得到上面的,我建议在 运行 你的例子之前的 ActionDispatch::Journey::Formatter.match_routes 中放置一个断点。

请注意,rspec-rails 控制器规范不使用路由来决定调用什么操作方法或在哪个控制器上调用它 class;它已经从传递给 describe 的控制器 class 和传递给操作方法(getpost 等)的操作中知道了它们。但是,它会查找路由并使用它来格式化请求环境。在其他用途​​中,它将路径放在 request.env['PATH_INFO'].

我在 Rails 4.1 中对此进行了调查,因为这是我手边的项目所使用的。对于 Rails.

的其他版本,它可能准确也可能不准确