How do I test the title of a page from an RSpec view spec?
I'm l开发者_JAVA技巧earning RSpec 2 with Rails 3. In order to set the contents of the tag in the layout for each page, I have a helper that can be used to set the title and then return it:
def page_title(subtitle=nil)
if @title.nil?
@title = ["Site Name"]
end
unless subtitle.nil?
@title << subtitle
end
@title.reverse.join " - "
end
The helper is called from both the layout, where it returns the title, and the individual views, where it sets the title. Now, I want to test in the view specs that the title is being set correctly. Since the layout is not rendered, I have decided to call page_title from the spec and check that the return value is what I expect it to be. However, this doesn't work, and always just returns "Site Name". What should I do?
To check the title of a page in a view spec try:
require "spec_helper"
describe "controller/view.html.erb" do
it "renders page title with 'Title | MySite'" do
render template: "controller/view", layout: "layouts/application"
rendered.should have_selector("title", text: "Title | MySite")
end
end
Because render is being called outside of the controller, it needs to be told about the layout.
I'm not sure if this is what you meant, but you could test the layout directly:
require 'spec_helper'
include ApplicationHelper
describe "layouts/application" do
it "should add subtitle to page title" do
page_title("Subtitle")
render
rendered.should have_selector('title:contains("Subtitle - Site Name")')
end
end
EDIT
You could also test that the page_title
method is called in the view:
describe "mycontroller/index" do
it "should set subtitle" do
view.should_receive(:page_title).with("Subtitle")
render
end
end
or you could use a controller test with render_views
:
describe Mycontroller do
render_views
it "sets the page title" do
get :index
response.body.should contain("Subtitle - Site Name")
end
end
精彩评论