2010-02-28 158 views
4

我是新手,我試圖用rspec測試一個控制器。我的第一個測試是當show action被調用時,它應該通過url查找一個Category。rspec的測試軌控制器

問題是,當我加入存根代碼,我得到以下錯誤:

未定義的方法`發現」的#

我的測試是這樣的:

require 'spec_helper' 

describe CategoriesController do 
    describe "GET /category-name/" do 
     before(:each) do 
      @category = mock_model(Category) 
      Category.stub!(:find).with(:first, :conditions => ["url = :url", {:url => "category-name"}]).and_return(@category) 
     end 

     it "should find the category by url" do 
      controller.show 
      Category.should_receive(:find).with(:first, :conditions => ["url = :url", {:url => "category-name"}]).and_return(@category) 
     end 
    end 
end 

回答

10

您的來電要求之後應該在should_receive之後。這是一件緊張的事情。所以它有這樣的讀法,「類別應該收到的東西,當發生這種情況」。 「發生這種情況」是指請求。

it "should find the category by url" do 
    Category.should_receive(:find).with... 
    get "show", { your params, if you're sending some in } 
end 

此外,你想去一個請求的方式與調用控制器方法本身,至少這個特定的測試。所以

post "action_name" 
get "action_name" 
update "action_name" 
delete "action_name" 

代替

controller.action_name 
+0

啊,太好了,謝謝。現在存根正常工作,但如果我嘗試使用獲取「顯示」,我得到一個錯誤說: 沒有路由匹配{:action =>「show」,:controller =>「categories」} 但耙路由返回: 根目錄/ {:控制器=>「類別」,:動作=>「索引」} – 2010-03-01 09:21:52

+0

我不知道,我已經解決了。我需要通過:URL得到:顯示這就是爲什麼它沒有找到我的路線。謝謝你的幫助 – 2010-03-01 09:47:13