Search code examples
ruby-on-railscapybararspec-railsrailstutorial.org

Rspec have_selector error when expected output is correct


I have 3 rspec selector fails when they all should be successes. I'm following along with the rails-tutorial.org book and his shows as correct.

PagesController GET 'home' should have the right title
     Failure/Error: response.should have_selector("title", :content => "Ruby on Rails     Sample App | Home")
       expected following output to contain a <title>Ruby on Rails Sample App | Home</title> tag:
   <!DOCTYPE html>
   <html>
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
   <title>Ruby on Rails Tutorial Sample App | Home</title>
   </head>

and the exact same errors with 'content' and 'about'

application.html.erb

<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
    <%= csrf_meta_tag %>
</head>
<body>
    <%= yield %>
</body>
</html>

home.html.erb

    <h1>Sample App</h1>
    <p>
    This is the home page for the <a href='http://railstutorial.org'>Ruby on Rails Tutorial</a> sample application
    </p>

application_helper.erb

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

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 Sample App |     Home")
    end

    it "should have a non-blank body" do
      get 'home'
      response.body.should_not =~ /<body>\s*<\/body>/
    end
  end

Solution

  • If you're using Capybara 2.0, invisible text like the title element is ignored. See the Capybara Github issue about it here.

    Rails Tutorial specifically uses Capybara version 1.1.2, so if you haven't done so, make sure you write explicit versions for all your gems as per the tutorial Gemfile.

    If you want to use Capybara 2.0, either now or in the future, see the following SO questions for assistance setting it up, as well as getting tests for the title element working again: