【发布时间】:2012-07-20 14:57:32
【问题描述】:
我在 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 => "#base_title} | Contact") 名称错误: # 未定义的局部变量或方法“base_title”
谁能告诉我这里出了什么问题?我怀疑这与辅助函数和 Rspec 无法识别的 base_title 变量有关,但根据教程,测试套件应该全部通过绿色。
更新:我知道为什么其中一项测试失败了。但是我仍然对这 3 个视图说 base_title 是一个未定义的方法有疑问。
【问题讨论】:
-
你检查我的答案了吗?
标签: ruby-on-rails rspec view-helpers