如何检查页面上元素的存在?

how to check the presence of the element on the page?

请帮忙解决问题。我使用 rails4 + rspec + 水豚。

我的页面有 title-element:

<!DOCTYPE html>

<html lang="ru">
  <head>
    <title>I am learning Rails</title>
    <link rel="stylesheet" media="all" href="/assets/albums.self855.css?body=1" data-turbolinks-track="true" />
    ......
    .........
    ........

rspec 测试:

require 'spec_helper'

describe ImagesController, type: :controller do
  describe "index action" do
    it 'render title-element on root page' do
      visit '/'
      #page.should have_selector 'head title', :visible => false
      page.should have_selector('head title',
                          :text => "Складик картинок")
    end  
  end  
end  

i 运行 在控制台中:

rspec spec

但控制台显示以下错误消息:

...F

Failures:

  1) ImagesController index action render title-element on root page
     Failure/Error: page.should have_selector('head title',
       expected to find css "head title" with text "I am learning Rails" but there were no matches
     # ./spec/controllers/images_controller_spec.rb:37:in `block (3 levels) in <top (required)>'

Finished in 0.94045 seconds (files took 1.95 seconds to load)
4 examples, 1 failure

Failed examples:

rspec ./spec/controllers/images_controller_spec.rb:30 # ImagesController index action render title-element on root page

更新答案:

原来,已经有一个have_title [Capybara RSpec matcher] 你可以用它来解决你的问题。

describe ImagesController, type: :controller do
  describe "index action" do
    it 'render title-element on root page' do
      visit '/'
      expect(page).to have_title "Складик картинок"
    end  
  end  
end 

标题元素未显示在页面上,因此水豚的普通查找器找不到它,但是您可以使用标题匹配器

page.should have_title('your title')