2010-03-25 123 views
1

我有一個名爲Xpmodule的Rails型號,並帶有相應的控制器XpmoduleController測試帶有RSpec和不同路由名稱的Ruby on Rails控制器

class XpmoduleController < ApplicationController 
    def index 
    @xpmodule = Xpmodule.find(params[:module_id]) 
    end 

    def subscribe 
    flash[:notice] = "You are now subscribed to #{params[:subscription][:title]}" 
    redirect_to :action => :index 
    end 
end 

最初的意圖是來命名其原因很明顯不起作用模型Module。不過,我還是希望有網址的樣子/module/4711/因此,我已將此添加到我的routes.rb

map.connect '/module/:module_id', :controller => 'xpmodule', :action => 'index' 

map.connect '/module/:module_id/subscribe', :controller => 'xpmodule', 
    :action => 'subscribe' 

現在我想使用RSpec來測試這個控制器:

describe XpmoduleController do 
    fixtures :xpmodules 
    context "index" do 
    it "should assign the current xpmodule" do 
     xpm = mock_model(Xpmodule) 
     Xpmodule.should_receive(:find).and_return(xpm) 
     get "index" 
     assigns[:xpmodule].should be_an_instance_of(Xpmodule) 
    end 
    end 
end 

對此我得到No route matches {:action=>"index", :controller=>"xpmodule"}。當然這是正確的,但我不想僅僅爲了測試目的而添加這條路線。有沒有辦法告訴Rspec在get中調用不同的URL?

回答

1

頭,碰壁,牆,碰頭。 bang

在SO上沒有得到答案是一個肯定的跡象,我應該更加努力。因此,我明確將/xpmodule路線添加到routes.rb。只是注意到測試仍然失敗。長話短說:

it "should assign the current xpmodule" do 
    xpm = mock_model(Xpmodule) 
    Xpmodule.should_receive(:find).and_return(xpm) 
    get "index", :module_id => 1 
    assigns[:xpmodule].should be_an_instance_of(Xpmodule) 
end 

是解決方案。

3

據我可以告訴你測試控制器的行爲,而不是路由到該行動。這是兩件不同的事情!

試試這個對於初學者:

it "should map xpmodules controller to /modules url" do 
    route_for(:controller => "xpmodule", :action => "index").should == "/modules" 
end 

申請其他操作爲好。如果你想做一個反向路由(從URL到控制器/動作),那麼這樣做:

it "should route /modules url to xpmodules controller and index action" do 
    params_from(:get, "/modules").should == {:controller => "xpmodules", :action => "index"} 
end 
+0

看到我的答案,我只是沒有調用正確的參數的行動。 – jhwist 2010-03-26 10:22:10