2010-11-19 68 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