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

时间:2011-02-26 20:06:21

标签: ruby-on-rails rspec capybara

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

8 个答案:

答案 0 :(得分:100)

由于capybara的版本 2.1.0 ,会话中有方法来处理标题。

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

所以你可以测试标题:

expect(page).to have_title "my_title"

根据github.com/jnicklas/capybara/issues/863,以下内容也适用于水豚 2.0

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

答案 1 :(得分:14)

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

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

答案 2 :(得分:13)

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

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

答案 3 :(得分:3)

我将此添加到我的规范助手:

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

然后我可以使用:

it 'should have the right title' do
  page.must_have_title('Expected Title')
end

答案 4 :(得分:2)

使用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

答案 5 :(得分:2)

为了测试使用Rspec和Capybara 2.1的页面标题,您可以使用

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

    另一种选择是

  2. expect(page).to have_css 'title', text: 'Title text', visible: false
    由于Capybara 2.1的默认值为Capybara.ignore_hidden_elements = true,并且因为title元素不可见,所以您需要选项visible: false才能使搜索包含不可见的页面元素。

答案 6 :(得分:0)

您只需将subject设置为page,然后为页面的title方法写一个期望值:

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

在上下文中:

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

答案 7 :(得分:-1)

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