views:

35

answers:

1

I'm learning 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?

A: 

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
zetetic
Thanks, but that's not what I was looking for. I'm trying to test that the view is setting the title correctly (by calling page_title) by checking the output of page_title to what I want that page to return. Like, it would be different for each view.
hatkirby
see my edit -- that help?
zetetic
Well, it wasn't what I was originally looking for, but I have decided to just test it from the controller spec. Thanks!
hatkirby