Capybara: How to test the title of a page?

2019-01-17 05:31发布

In a Rails 3 application using Steak, Capybara and RSpec how do I test the page's title?

8条回答
小情绪 Triste *
2楼-- · 2019-01-17 05:50

In order to test for the title of a page with Rspec and Capybara 2.1 you could use

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

    another option is

  2. expect(page).to have_css 'title', text: 'Title text', visible: false
    Since Capybara 2.1 the default is Capybara.ignore_hidden_elements = true, and because the title element is invisible you need the option visible: false for the search to include non visible page elements.

查看更多
三岁会撩人
3楼-- · 2019-01-17 05:51

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

查看更多
Summer. ? 凉城
4楼-- · 2019-01-17 05:53

This works under Rails 3.1.10, Capybara 2.0.2 and Rspec 2.12, and allows matching partial contents:

find('title').native.text.should have_content("Status of your account::")
查看更多
我想做一个坏孩纸
5楼-- · 2019-01-17 05:54

Testing the Title of each page can be done in a much easier way 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
查看更多
Juvenile、少年°
6楼-- · 2019-01-17 06:01

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
查看更多
手持菜刀,她持情操
7楼-- · 2019-01-17 06:02

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

page.should have_xpath("//title", :text => "My Title")
查看更多
登录 后发表回答