Capybara: How to check the page title?

In a Rails 3 application using Steak, Capybara and RSpec, how to check the page title?

+63
ruby-on-rails rspec capybara
Feb 26 2018-11-21T00:
source share
8 answers

Since version 2.1.0 is capybara, there are methods for working with the header in the session. You

page.title page.has_title? "my title" page.has_no_title? "my not found title" 

So you can check the name, for example:

 expect(page).to have_title "my_title" 

According to github.com/jnicklas/capybara/issues/863 , also works with capybara 2.0 :

 expect(first('title').native.text).to eq "my title" 
+97
Jan 03 '13 at 13:24
source share

This works under Rails 3.1.10, Capybara 2.0.2 and Rspec 2.12 and allows partial content to be mapped:

 find('title').native.text.should have_content("Status of your account::") 
+14
Feb 06 '13 at 20:14
source share

You should be able to search for the title element to make sure that it contains the desired text:

 page.should have_xpath("//title", :text => "My Title") 
+13
Feb 26 '11 at 20:27
source share

Testing the title of each page can be much easier with RSpec.

 require 'spec_helper' describe PagesController do render_views describe "GET 'home'" do before(:each) do get 'home' @base_title = "Ruby on Rails" end it "should have the correct title " do response.should have_selector("title", :content => @base_title + " | Home") end end end 
+2
Feb 26 2018-11-21T00:
source share

I added this to my spec helper:

 class Capybara::Session def must_have_title(title="") find('title').native.text.must_have_content(title) end end 

Then I can just use:

 it 'should have the right title' do page.must_have_title('Expected Title') end 
+2
Feb 28 '13 at 21:50
source share

To check the page name with Rspec and Capybara 2.1, you can use

  • expect(page).to have_title 'Title text'

    another option

  • expect(page).to have_css 'title', text: 'Title text', visible: false
    Since Capybara 2.1 by default is Capybara.ignore_hidden_elements = true , but because the title element is invisible, you will need the visible: false option so that the search includes invisible page elements.

+2
Sep 15 '14 at 13:40
source share

You just need to set subject to page , and then write the wait for the title method:

 subject{ page } its(:title){ should eq 'welcome to my website!' } 

In the context:

 require 'spec_helper' describe 'static welcome pages' do subject { page } describe 'visit /welcome' do before { visit '/welcome' } its(:title){ should eq 'welcome to my website!'} end end 
0
Feb 21 '14 at 19:31
source share

it { should have_selector "title", text: full_title("Your title here") }

-one
Mar 17 '13 at 1:22
source share



All Articles