The have_selector fails in an RSpec test but page renders correctly and the tag is present

Steve T picture Steve T · Mar 13, 2011 · Viewed 11.9k times · Source

I'm working my way through the Rails Tutorial book by Hartl and I'm completely stuck on one of the tests. The test (right from the book) is very simple:

require 'spec_helper'
describe UsersController do
render_views
describe "GET 'show'" do
    before(:each) do
        @user = Factory(:user)
    end
    ...
    it "should include the user's name" do
        get :show, :id => @user
        response.should have_selector('h1', :content => @user.name)
    end
end

The test fails with the following error:

UsersController GET 'show' should include the user's name Failure/Error: response.should have_selector('h1', :content => @user.name) expected following output to contain a <h1>Steve T</h1> tag:...

The page renders properly in the browser. Here is a snipped from the HTML source rendered by the browser:

<section class="round">
<h1> <img alt="Steve T" class="gravatar" src="http://gravatar.com/..." /> Steve T </h1> </section>

I can even add a call to: print response.body in the controller spec and it will output the tags properly.

Any ideas on what I may be doing wrong?

UPDATE - It seems like we have identified a potentially significant item: The HTML in the rspec test failure message is missing the body tag everything inside it.

1) UsersController GET 'show' should include the user's name Failure/Error: response.should have_selector('h1', :content => @user.name) expected following output to contain a <h1>Steve T</h1> tag: <!DOCTYPE html> <html><head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Ruby on Rails Tutorial Sample App | Steve T</title> </head></html> # ./spec/controllers/users_controller_spec.rb:33:in block (3 levels) in <top (required)>'

Does anyone know why, if the page in the browser includes the <body> tags and the inner content and if print response.body shows the content, why would the error message skip it?

Answer

atpark333 picture atpark333 · Aug 17, 2011

I had a similar problem when working through the Rails Tutorial. I forgot to include 'render_views' below the top 'describe' statement, which was causing the 'have_selector' test to fail.