【问题标题】:how to check the presence of the element on the page?如何检查页面上元素的存在?
【发布时间】:2015-08-16 10:27:15
【问题描述】:

请帮助解决问题。我使用 rails4 + rspec + capybara。

我的页面有标题元素:

<!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  

我在控制台中运行:

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

【问题讨论】:

  • "складик картинок" - 太可爱了:)

标签: ruby-on-rails ruby-on-rails-4 rspec capybara


【解决方案1】:

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

page.should have_title('your title')

【讨论】:

  • errormessage: Failure/Error: page.should have_title('I am learning Rails') 预期 "" 包含 "I am learning Rails"
  • 所以它找到了一个空白标题,或者页面上没有标题 - 您确定正在加载正确的页面吗?您的页面没有在 Capybara.default_wait_time 秒内加载吗? - 您可以通过在 page.should have_tittle 之前放置 sleep 10 或其他内容来测试时间。
  • 我刚刚注意到测试的类型是 :controller - capybara 真的是为功能测试而设计的,请尝试 type: :feature
【解决方案2】:

更新答案:

原来,已经有一个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 

【讨论】:

  • “我正在学习 Rails”上的替换短语和“标题”上的更改选择器未解决问题。错误信息是一样的
  • 你真的不应该求助于查询源,你可以将 visible: false 传递给 have_selector 但最好的解决方案是使用我的答案中所示的 have_title 匹配器
猜你喜欢
  • 2021-02-23
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
  • 2011-09-25
  • 1970-01-01
  • 1970-01-01
  • 2015-05-30
相关资源
最近更新 更多