2011-08-23 99 views
2

我有以下助手方法(應用程序/傭工/ application_helper.rb):問題與導軌的輔助方法

module ApplicationHelper 

#Return a title on a per-page basis 
def title 
    base_title = "Ruby on Rails Tutorial Sample App" 
    if @title.nil? 
    base_title 
    else 
    "#{base_title} | #{@title}" 
    end 
end 
end 

和這裏的僱員再培訓局(應用程序/視圖/佈局/ application.html.erb):

<!DOCTYPE html> 
<html> 
    <head> 
    <title><%= title %></title> 
    <%= csrf_meta_tag %> 
    </head> 
    <body> 
    <%= yield %> 
    </body> 
</html> 

我跑了一個rspec測試,看看這個輔助方法是否工作,看起來它不能找到標題。

這裏的錯誤消息:

Failures: 

    1) PagesController GET 'home' should be successful 
    Failure/Error: get 'home' 
    ActionView::Template::Error: 
     undefined local variable or method `title' for #<#<Class:0x991ecb4>:0x991315c> 
    # ./app/views/layouts/application.html.erb:4:in `_app_views_layouts_application_html_erb__248109341_80250010__979063050' 
    # ./spec/controllers/pages_controller_spec.rb:8:in `block (3 levels) in <top (required)>' 

    2) PagesController GET 'home' should have the right title 
    Failure/Error: get 'home' 
    ActionView::Template::Error: 
     undefined local variable or method `title' for #<#<Class:0x991ecb4>:0x9d7d094> 
    # ./app/views/layouts/application.html.erb:4:in `_app_views_layouts_application_html_erb__248109341_82566280__979063050' 
    # ./spec/controllers/pages_controller_spec.rb:13:in `block (3 levels) in <top (required)>' 

誰能告訴我我做錯了什麼?

UPDATE:

我包括通過執行以下操作助手:

describe PagesController do 
     include ApplicationHelper 
     render_views 

     describe "GET 'home'" do 
     it "should be successful" do 
      get 'home' 
      response.should be_success 
     end 

     it "should have the right title" do 
     get 'home' 
     response.should have_selector("title", 
         :content => "Ruby on Rails Tutorial Sample App | Home") 
    end 
    end 


//and some more 

但我仍然得到同樣的錯誤

回答

2

在你的意見,傭工不包括由默認。

您可以mock out the helper methods using the template object

template.should_receive(:title).and_return("Title") 

然後,您可以單獨測試helpers

或者,你可以簡單地做包括您在您的視圖規範助手:

include ApplicationHelper 

編輯

describe PagesController do 
    include ApplicationHelper 

    describe "GET 'home'" do 
    it "should be successful" do 
     controller.template.should_receive(:title).and_return("Title") 
     get 'home' 
     response.should be_success 
    end 
    end 
end 
+0

在哪裏我把包括ApplicationHelper在哪裏? – adit

+0

如果我沒有記錯,它需要在描述塊內。 **編輯**剛剛發現這個鏈接http://www.multunus.com/2011/06/rspec-issue-with-include-helper-in-spec/ – Gazler

+0

我編輯了我的問題上面,請檢查 – adit