2011-03-17 108 views
1

我想測試我的文章控制器,它使用命名的路由(/永久/條件方面的使用)的永久行動:如何在使用RSpec測試控制器時調用Rails命名的路由?

map.permalink 'permalink/:permalink', 
       :controller => :articles, :action => :permalink, :as => :permalink 

這是規格:

describe "GET permalink" do 
    it "should visit an article" do 
    get "/permalink/@article.permalink" 
    end 
end 

但是,我得到這個錯誤:

的ActionController :: RoutingError在 'ArticlesController永久呈現頁面' 沒有路由匹配{:控制器=> 「文章」,:動作=> 「/ permalink/@article.permalink」}

更新:

任何想法如何編寫GET?

回答

1

錯誤是因爲您要將整個URL傳遞給需要控制器操作方法之一的名稱的方法。如果我理解正確,那麼你就試圖一次測試幾件事情。

測試路由名稱與測試路由不同從測試控制器操作不同。以下是我如何測試控制器操作(這可能並不令人意外)。請注意,我符合你的命名,而不是推薦我使用的。

在投機/控制器/ articles_controller_spec.rb,

describe ArticlesController do 
    describe '#permalink' do 
    it "renders the page" do 
     # The action and its parameter are both named permalink 
     get :permalink :permalink => 666 
     response.should be_success 
     # etc. 
    end 
    end 
end 

下面是我如何測試一個名爲路線只有RSpec的護欄:

在投機/路由/ articles_routing_spec.rb,

describe ArticlesController do 
    describe 'permalink' do 

    it 'has a named route' do 
     articles_permalink(666).should == '/permalink/666' 
    end 

    it 'is routed to' do 
     { :get => '/permalink/666' }.should route_to(
     :controller => 'articles', :action => 'permalink', :id => '666') 
    end 

    end 
end 

Shoulda的路由匹配器更簡潔,但仍提供了一個很好的描述和失敗消息:

describe ArticlesController do 
    describe 'permalink' do 

    it 'has a named route' do 
     articles_permalink(666).should == '/permalink/666' 
    end 

    it { should route(:get, '/permalink/666').to(
     :controller => 'articles', :action => 'permalink', :id => '666' }) 

    end 
end 

AFAIK既不RSpec也不應該有一個具體,簡明的測試命名路線的方式,但你可以寫你自己的匹配器。

+0

與我們的第一個例子我得到一個路由錯誤,我需要測試'permalink/a_name'。對不起,我的問題不清楚。我需要測試永久鏈接動作,但我正在使用命名路由。我需要知道正確的語法才能獲得... – rtacconi 2011-03-30 13:49:08

+0

當您測試動作時,不要擔心它的路線。只需像上面第一個代碼示例那樣直接測試操作。測試路線是一個不同的問題;看到另外兩個例子。 – 2011-03-30 18:04:38

+0

你的第一個例子不起作用,因爲一個get在URL中創建了文章,即/ articles/permalink/name_of_article,但我需要/ permalink/name_of_the_article和RSpec不允許我這樣做。 – rtacconi 2011-03-30 19:57:24

0
describe "GET permalink" do 
    it "should visit an article" do 
    get "/permalink/#{@article.permalink}" 
    end 
end 
+3

不,我得到這個:ActionController :: RoutingError在'ArticlesController GET永久鏈接應該訪問一篇文章' 沒有路由匹配{:controller =>「articles」,:action =>「/ permalink/link」} – rtacconi 2011-11-18 10:16:19

相關問題