sokdev
sokdev

Reputation: 73

RSpec/Capybara testing have_selector conundrum

This is from Ruby on Rails Tutorial by Michael Hartl 2nd edition. The 3rd (and currently latest) edition does not test with RSpec so I decided to use this book.

I've read users' workarounds and know there are different ways to write the test to make it work but I want to use have_selector to keep the code consistent. Any explanation/advice would be very helpful. I do not understand why the below test passes for the h1 element and not the title element:

spec.rb:

describe "Static pages" do 

  describe "Home page" do

  it "should have the h1 'Sample App'" do
    visit '/static_pages/home'
    expect(page).to have_selector('h1', :text => 'Sample App')
  end

  it "should have the title 'Home'" do
    visit '/static_pages/home'
    expect(page).to have_selector('title', 
                         :text => "Ruby on Rails Tutorial Sample App | Home")
  end
end

home.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Ruby on Rails Tutorial Sample App | Home</title>
</head>
<body>
  <h1>Sample App</h1>

</body>
</html>

Upvotes: 7

Views: 3002

Answers (2)

Thomas Walpole
Thomas Walpole

Reputation: 49890

Updating this for current capybara best practices since there is a have_title matcher now.

expect(page).to have_title('Ruby on Rails Tutorial Sample App | Home')

Upvotes: 3

Prakash Murthy
Prakash Murthy

Reputation: 13067

Try:

expect(page).to have_selector('title', 
                     :text => "Ruby on Rails Tutorial Sample App | Home",
                     :visible => false)

Since the title tag is in <head> element, it is considered hidden. Specifying :visible => false includes those tags for consideration in the have_selector matcher.

Upvotes: 9

Related Questions