2015-08-24 36 views
-1

我試圖寫一個測試SessionsController,我寫道:如何編寫路由規格測試 - 軌道4

我使用規格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:增加了完整的測試代碼

+1

你收到了什麼錯誤信息? – margo

+0

我編輯了我的問題以包含我收到的錯誤。它基本上只是說測試失敗了。 – WagnerMatosUK

+1

它取決於你正在使用的RSpec版本,但不可能是你缺少指定測試類型':type =>:controller'? – muichkine

回答

1

必須指定type: :routing和使用assert_routing它有封地來測試2種方式的路線(路線代和路由匹配)

我把我的答案作爲一般,所以其他人可以從中獲取信息,請適應你的情況

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_generatesassert_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