在使用Steak,Capybara和RSpec的Rails 3应用程序中,如何测试页面标题?
在使用Steak,Capybara和RSpec的Rails 3应用程序中,如何测试页面标题?
自版本 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"
这适用于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")
我把它添加到我的规范助手:
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
使用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
为了测试使用Rspec和Capybara 2.1的页面标题,您可以使用
expect(page).to have_title 'Title text'
另一种选择是
expect(page).to have_css 'title', text: 'Title text', visible: false
由于Capybara 2.1的默认值是 Capybara.ignore_hidden_elements = true
,因为title元素是不可见的,你需要选项 visible: false
搜索包括不可见的页面元素。
你只需要设置 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
it { should have_selector "title", text: full_title("Your title here") }