运行Rspec时,我遇到了三种相同类型的错误。
我的application_controller.rb是:
<!DOCTYPE>
<html>
<head>
<title><%= @title %></title>
<%= csrf_meta_tag %>
</head>
<body>
<%= yield %>
</body>
</html>
我的pages_controller_spec.rb是:
require 'spec_helper'
describe PagesController do
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 | Home")
end
it "should have a non-blank body" do
get 'home'
response.body.should_not =~ /<body>\s*<\/body>/
end
end
describe "GET 'contact'" do
it "should be successful" do
get 'contact'
response.should be_success
end
it "should have the right title" do
get 'contact'
response.should have_selector("title",
:content => "Ruby on Rails Tutorial Sample | Contact")
end
end
describe "GET 'about'" do
it "should be successful" do
get 'about'
response.should be_success
end
it "should have the right title" do
get 'about'
response.should have_selector("title",
:content => "Ruby on Rails Tutorial Sample | About")
end
end
end
我的错误读出是:
7 examples, 3 failures
Failed examples:
rspec ./spec/controllers/pages_controller_spec.rb:12 # PagesController GET 'home' should have the right title
rspec ./spec/controllers/pages_controller_spec.rb:30 # PagesController GET 'contact' should have the right title
rspec ./spec/controllers/pages_controller_spec.rb:43 # PagesController GET 'about' should have the right title
我的application.html.erb
<!DOCTYPE>
<html>
<head>
<title><%= @title %></title>
<%= csrf_meta_tag %>
</head>
<body>
<%= yield %>
</body>
</html>
这是我的帮助文件:
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
这是我的页面控制器文件:
class PagesController < ApplicationController
def home
@title = "Home"
end
def contact
@title = "Contact"
end
def about
@title = "About"
end
end
我不清楚为什么会失败。
答案 0 :(得分:2)
将application.html.erb更改为读取title
而不是@title
,因为您正在使用辅助方法,而不是从控制器设置标题。
<!DOCTYPE>
<html>
<head>
<title><%= title %></title>
<%= csrf_meta_tag %>
</head>
<body>
<%= yield %>
</body>
</html>