如何为路由编写规范测试 - Rails 4

How to write Spec tests for routes - Rails 4

我正在尝试为 SessionsController 编写测试,我写了以下内容:

我正在使用规范 3.3

    RSpec.describe SessionsController, type: :controller do

        describe SessionsController do

            describe "POST create" do 

                it "sign in should have a valid route" do
                    post('/api/signin').should route_to('api/sessions#create')
                end

            end

        end

    end

此应用主要用作 API,因此目前不需要查看。

在我的路线中,我有以下内容:

match     '/api/signin',                          to: 'api/sessions#create',

但是测试没有通过。

有什么建议吗?

编辑:错误:

rspec ./spec/controllers/sessions_controller_spec.rb:27 # SessionsController SessionsController POST create sign in should have a valid route
rspec ./spec/controllers/sessions_controller_spec.rb:31 # SessionsController SessionsController POST create creates a new session

EDIT2:添加了完整的测试代码

您必须指定 type: :routing 并使用 assert_routing 这有利于以两种方式测试您的路线(路线生成和路线匹配)

我的回答是笼统的,所以其他人可以从中获取信息,请根据您的情况进行调整

describe MyController, type: :routing do
  it 'routing' do
    # This is optional, but also a good reminder to tell me when I add a route
    #   and forgot to update my specs.
    #   Please see bellow for the helper definition
    expect(number_of_routes_for('my_controller')).to eq(8)

    # Then test for the routes, one by one
    assert_routing({method: :get, path: '/my_controller'},   {controller: 'my_controller', action: 'index'})
    assert_routing({method: :get, path: '/my_controller/1'}, {controller: 'my_controller', action: 'show', id: '1'})
    # ... And so on, for each route
  end
end

注意:如果assert_routing出现错误(我猜match会出现这种情况,但我不记得了)然后有看看 assert_generates and assert_recognizes


还有 number_of_routes_for 助手

def number_of_routes_for(controller)
  Rails.application.routes.routes.to_a.select{ |r| r.defaults[:controller] == controller }.count
end