1

我想在我的文章控制器中测试永久链接操作,它使用命名路由(/permalink/terms-of-use):

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

但我得到这个错误:

'ArticlesController 永久链接呈现页面'中的 ActionController::RoutingError 没有路由匹配 {:controller=>"articles", :action=>"/permalink/@article.permalink"}

更新:

知道如何编写 GET 吗?

4

2 回答 2

4

该错误是因为您将整个 URL 传递给需要控制器操作方法之一的名称的方法。如果我理解正确,您正在尝试一次测试几件事。

测试一个路由有一个名字不同于测试一个路由和测试一个控制器动作是不同的。这是我测试控制器操作的方法(这可能不足为奇)。请注意,我正在匹配您的命名,而不是推荐我使用的名称。

在 spec/controllers/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-rails 测试命名路由的方法:

在 spec/routing/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 和 Shoulda 都没有测试命名路由的具体、简洁的方法,但您可以编写自己的匹配器。

于 2011-03-20T20:21:32.907 回答
0
describe "GET permalink" do
  it "should visit an article" do
    get "/permalink/#{@article.permalink}"
  end
end
于 2011-08-12T10:54:09.487 回答