2010-11-19 97 views
3

我有一個無法直接訪問的控制器,而是以傳統的RESTful方式直接訪問,而只能通過特定的URL訪問。測試無法直接訪問的RSpec控制器動作

通常我習慣於在我的控制器規格中使用get和post來調用控制器動作。有沒有一種方法可以通過訪問特定的URL來鍛鍊我的控制器?

編輯:

這裏是我的路線:

Larzworld::Application.routes.draw do 

    match '/auth/:provider/callback' => 'authentications#create' 

    devise_for :users, :controllers => {:registrations => "registrations"} 

    root :to => 'pages#home' 
end 

這裏是我的規格:

require 'spec_helper' 

describe AuthenticationsController do 

before(:each) do 
    request.env["omniauth.auth"] = {"provider" => "twitter", "uid" => "12345678"} 
end 

describe 'POST create' do 

    it "should find the Authentication using the uid and provider from omniauth" do 
    Authentication.should_receive(:find_by_provider_and_uid) 
    post 'auth/twitter/callback' 
    end 
end 

end 

和以下是錯誤我收到:

Failures: 
    1) AuthenticationsController POST create should find the Authentication using the uid and provider from omniauth 
    Failure/Error: post 'auth/twitter/callback' 
    No route matches {:action=>"auth/twitter/callback", :controller=>"authentications"} 
    # ./spec/controllers/authentications_controller_spec.rb:13 

Finished in 0.04878 seconds 
1 example, 1 failure 

回答

7

控制器測試使用四個HTTP動詞(G ET,POST,PUT,DELETE),無論您的控制器是否爲RESTful。所以,如果你有一個非RESTful路線(Rails3中)

match 'example' => 'story#example' 

在這兩項測試:

require 'spec_helper' 

describe StoryController do 

    describe "GET 'example'" do 
    it "should be successful" do 
     get :example 
     response.should be_success 
    end 
    end 

    describe "POST 'example'" do 
    it "should be successful" do 
     post :example 
     response.should be_success 
    end 
    end 

end 

將兩者通,因爲路線接受任何動詞。

編輯

我想你混淆了控制器的測試和路由測試。在控制器測試中,您要檢查操作的邏輯是否正常工作。在路由測試中,您檢查URL是否到達正確的控制器/操作,並且正確生成了params散列。

所以來測試你的控制器動作,簡單地做:

post :create, :provider => "twitter"` 

要測試的路線,使用params_from(對Rspec的1)或route_to(對Rspec的2):

describe "routing" do 
    it "routes /auth/:provider/callback" do 
    { :post => "/auth/twitter/callback" }.should route_to(
     :controller => "authentications", 
     :action => "create", 
     :provider => "twitter") 
    end 
end 
+0

OK,那是我的想法,但看看我編輯的職位,我發佈我的路線,我的測試和我的錯誤。我不明白爲什麼它沒有將其映射到正確的行動。 – TheDelChop 2010-11-19 19:59:40

+0

看我的編輯。我想,你真的想在這裏進行路由測試。 – zetetic 2010-11-19 21:18:30