在使用Steak,Capybara和RSpec的Rails 3应用程序中,如何测试页面标题?
Answers:
自从水豚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,以下内容也适用于capybara 2.0:
expect(first('title').native.text).to eq "my title"
您应该能够搜索该title
元素以确保其包含所需的文本:
page.should have_xpath("//title", :text => "My Title")
page.should have_content('<title>Your Title</title>')
使用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
您只需要将设置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