简体   繁体   English

Capybara:如何测试页面的标题?

[英]Capybara: How to test the title of a page?

在使用Steak,Capybara和RSpec的Rails 3应用程序中,如何测试页面标题?

Since the version 2.1.0 of capybara there are methods on the session to deal with the title. 从版本2.1.0的水豚到会话上有方法来处理标题。 You have 你有

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

So you can test the title like: 所以你可以测试标题:

expect(page).to have_title "my_title"

According to github.com/jnicklas/capybara/issues/863 the following is also working with capybara 2.0 : 根据github.com/jnicklas/capybara/issues/863 ,以下内容也与capybara 2.0合作

expect(first('title').native.text).to eq "my title"

这适用于Rails 3.1.10,Capybara 2.0.2和Rspec 2.12,并允许匹配部分内容:

find('title').native.text.should have_content("Status of your account::")

您应该能够搜索title元素以确保它包含您想要的文本:

page.should have_xpath("//title", :text => "My Title")

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

In order to test for the title of a page with Rspec and Capybara 2.1 you could use 为了测试使用Rspec和Capybara 2.1的页面标题,您可以使用

  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. 由于Capybara 2.1的默认值是Capybara.ignore_hidden_elements = true ,并且因为title元素是不可见的,所以你需要选项visible: false来搜索包含不可见的页面元素。

Testing the Title of each page can be done in a much easier way with RSpec. 使用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

You just need to set the subject to page and then write an expectation for the page's title method: 您只需将subject设置为page ,然后为页面的title方法写下期望:

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

In 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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM