2010-03-25 120 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