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

时间:2016-05-25 12:33:31

标签: ruby-on-rails ruby rspec rspec-rails

我有一个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到路线/services/:id/add_comment并想要确定路线的确切位置。

我的routes.rb此路线:

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

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容打印rspec-rails controller规范中使用的路由名称:

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控制器规范并未使用该路由来决定要调用的操作方法或调用它的控制器类;它已经从您传递给describe的控制器类以及传递给操作方法的操作(getpost等)知道它们。但是,它确实查找路由并使用它来格式化请求环境。在其他用途​​中,它将路径放在request.env['PATH_INFO']

我在Rails 4.1中对此进行了调查,因为那是我所用的项目。对于其他版本的Rails,它可能准确也可能不准确。

相关问题