2011-03-17 54 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

相关问题