2014-11-02 107 views
0

我有这样的测试:RSpec的“无路由匹配”错误,但它们匹配

RSpec.describe RestaursController, :type => :controller do 

    context "GET /restaurs/:id" do 
    before do 
     @rest = FactoryGirl.create :restaur 
    end 

    context "resource exists" do 
     subject { get "restaurs/#{@rest.id}"} 
     it { expect(subject).to render_template(:show) } 
    end 

    context "resource doesn't exists" do 
     subject { get "restaurs/#{@rest.id + 1}" } 
     it { expect(subject).to redirect_to(:root) } 
    end 
    end 
end 

当我运行这些测试RSpec的说:

Failure/Error: subject { get "restaurs/#{@rest.id}"} 
ActionController::UrlGenerationError: 
    No route matches {:action=>"restaurs/7", :controller=>"restaurs"} 

但我认为我的路线是确定。看看rake routes日志

 Prefix Verb URI Pattern     Controller#Action 
    restaurs GET /restaurs(.:format)   restaurs#index 
      POST /restaurs(.:format)   restaurs#create 
new_restaur GET /restaurs/new(.:format)  restaurs#new 
edit_restaur GET /restaurs/:id/edit(.:format) restaurs#edit 
    restaur GET /restaurs/:id(.:format)  restaurs#show 
      PATCH /restaurs/:id(.:format)  restaurs#update 
      PUT /restaurs/:id(.:format)  restaurs#update 
      DELETE /restaurs/:id(.:format)  restaurs#destroy 
     root GET /       restaurs#index 

你有什么想法吗?问题是什么?也许这是关于RSpec语法或类似的东西?

回答

2

这不是你如何在控制器测试中的动作getget的参数是动作的名称,而不是可路由的路径。路由不涉及测试控制器,也不是rake routes

你给它的动作名称“餐厅/ 7”,这显然不是你的控制器上的方法的真实名称。相反,你应该使用get :show调用实际的方法“显示”您的控制器上,然后传递的参数的散列:

get :show, id: @rest.id + 1 

同样,你可以使用get :index,不get "/",你就可以使用get :edit, id: ...,不是get "/restaurs/#{...}/edit"。这是你想要在你的控制器上测试的实际方法,而不是一条路线是否会将你引向正确的方法。

作为一个相关的一边,你的开放背景是不合适的。您不应该使用GET /restaurs:/:id作为上下文。这里不涉及路由。只需测试方法名称即可。

相关问题