我有以下帮助方法(app / helpers / 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
这里是erb(app / views / layouts / 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)>'
谁能告诉我我做错了什么?
更新
我通过执行以下操作来包含帮助程序:
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
但是我仍然遇到同样的错误
答案 0 :(得分: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