我在Michael Hartl的RoR教程的第4章,并且在使用rspec和使用full_title帮助函数时遇到了一些麻烦。在本教程的第4.1部分中,我有如下的帮助程序代码。它的目的是使我的帮助,联系,家庭和页面不需要在每个视图上提供标题。
module ApplicationHelper
# Returns the full title on a per-page basis.
def full_title(page_title)
base_title = "Ruby on Rails Tutorial Sample App"
if page_title.empty?
base_title
else
"#{base_title} | #{page_title}"
end
end
端
我的布局页面看起来像
<!DOCTYPE html>
<html>
<head>
<title><title><%= full_title(yield(:title)) %></title></title>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
和我的static_pages_spec.rb文件如下所示:
require 'spec_helper'
describe "Static Pages" do
include ApplicationHelper
describe "Home page" do
it "should have the h1 'Sample App'" do
visit '/static_pages/home'
page.should have_selector('h1', :text => 'Sample App')
end
it "should have the base title 'Home'" do
visit '/static_pages/home'
page.should have_selector('title',
:text => "Ruby on Rails Tutorial App")
end
it "should not have a custom page title" do
visit '/static_pages/home'
page.should_not have_selector('title', :text => '| Home')
end
end
describe "Help page" do
it "should have the h1 'Help'" do
visit '/static_pages/help'
page.should have_selector('h1', :text => 'Help')
end
it "should have the right title 'Help'" do
visit '/static_pages/help'
page.should have_selector('title',
:text => "#{base_title} | Help")
end
end
describe "About us" do
it "should have the h1 'About Us'" do
visit '/static_pages/about'
page.should have_selector("h1", :text => "About Us")
end
it "should have the right title 'About Us'" do
visit '/static_pages/about'
page.should have_selector('title',
:text => "#{base_title} | About Us")
end
end
describe "Contact" do
it "should have the h1 'Contact'" do
visit '/static_pages/contact'
page.should have_selector('h1', :text => "Contact")
end
it "should have the right title 'Contact'" do
visit '/static_pages/contact'
page.should have_selector('title',
:text => "#{base_title} | Contact")
end
end
end
然而,当我运行rspec时,我得到4次测试失败。其中3个是指联系人,关于我们和帮助页面,并说出了
的内容失败/错误:: text =&gt; “#base_title} |联络”) NameError: 未定义的局部变量或方法“base_title”for#
谁能告诉我这里出了什么问题?我怀疑它与辅助函数和Rspec无法识别的base_title变量有关,但根据教程,测试套件应该全部传递绿色。
更新:我弄清楚为什么其中一项测试失败了。但我仍然对这3个视图有问题,说base_title是一个未定义的方法。
答案 0 :(得分:0)
在下面的测试中,rspect如何知道什么是base_title
(最后一行)。
describe "Help page" do
it "should have the h1 'Help'" do
visit '/static_pages/help'
page.should have_selector('h1', :text => 'Help')
end
it "should have the right title 'Help'" do
visit '/static_pages/help'
page.should have_selector('title',
:text => "#{base_title} | Help")
end
end
您尚未对其进行定义。我猜这就是你的测试失败的原因。