[rspec-users] Rails View spec testing for content in <head>

David Chelimsky dchelimsky at gmail.com
Sun Aug 22 14:25:21 EDT 2010

On Aug 20, 2010, at 1:16 PM, Michael Kintzer wrote:

> Hi,
> Was trying to verify content in a title tag within a head tag using
> RSpec2/Rails3 and a view spec, but it seems that render/rendered API's
> only return the html within the body tag.   In my case the head tag is
> defined in a Rails layout file, with a yield :title, and the title tag
> content is set via a content_for :title section within the view, ala
> http://railscasts.com/episodes/30-pretty-page-title.
> Is there a way to validate head content in a view spec?
> Thanks,
> -Michael
> Example
> ---
> require "spec_helper"
> describe "users/sessions/new.html.erb" do
>  describe "head" do
>    it "should have a head" do
>      render
>      rendered.should have_selector("head")
>    end
>  end
> end
>  Failure/Error: rendered.should have_selector("head")
>    expected following output to contain a <head/> tag:
>    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
> "http://www.w3.org/TR/REC-html40/loose.dtd">
>    <html><body>...

The render method you see in a view spec delegates to the render method in ActionView::TestCase, which, in turn, delegates to view.render. Within rails, view.render is called usually by a controller, which provides all the necessary context information, like what layout to render. In this case, because you are specifying things that happen in a layout, you need to provide that context information in the spec:

  render :template => "users/sessions, :layout => "layouts/application"

Note that you need to include ":template => ..." because RSpec's render method only sets the template if there are no arguments.


> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

More information about the rspec-users mailing list