问题 Capybara / RSpec'have_css'匹配器不工作但has_css确实如此


在使用Ruby 2的Rails 3.2.14应用程序中,使用rspec-rails 2.14.0和capybara 2.1.0,以下功能规范导致失败:

require 'spec_helper'

feature 'View the homepage' do
  scenario 'user sees relevant page title' do
    visit root_path
    expect(page).to have_css('title', text: "Todo")
  end
end

失败消息是:

 1) View the homepage user sees relevant page title
 Failure/Error: expect(page).to have_css('title', text: "Todo")
 Capybara::ExpectationNotMet:
   expected to find css "title" with text "Todo" but there were no matches. Also
   found "", which matched the selector but not all filters.

标题元素和正确的文本  在呈现的页面上

但是当我在功能规范中更改此行时:

expect(page).to have_css('title', text: "Todo")

对此:

page.has_css?('title', text: "Todo")

然后测试通过。 [编辑 - 但请参阅以下来自@JustinKo的回复,该测试不是一个好的测试,因为它总是会通过]

我如何得到 have_css(...) 形式工作?这是配置问题吗?

这是我的相关部分 Gemfile

group :development, :test do
  gem 'rspec-rails' 
  gem 'capybara'
end

和我的 spec/spec_helper.rb 设置如下:

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'capybara/rails'
require 'capybara/rspec'

Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

RSpec.configure do |config|

  # out of the box rspec config code ommitted

  config.include Capybara::DSL
end

谁知道我可能做错了什么?


2764
2017-10-22 13:51


起源

请继续阅读这篇文章,尤其是水豚部分 nofail.de/2013/10/debugging-rails-applications-in-development - phoet
如果你这样做的话 page.has_css?('title', text: "Todo"),测试将永远通过。 has_css? 只返回true或false,这不足以使测试失败。如果输出它,您可能会发现它是错误的。你确定该页面有一个带文字的标题元素吗? - Justin Ko
@JustinKo感谢你指出新手的错误。是的,标题显示的是相应的文本 - 在浏览器中检查。 - Tim Jones
你确定它是'标题'元素而不是'H2'或'H3'? - Backnol


答案:


默认情况下,Capybara只查找“可见”元素。 head元素(及其title元素)实际上并不可见。这导致在have_css中忽略title元素。

你可以强制Capybara也考虑不可见的元素 :visible => false 选项。

expect(page).to have_css('title', :text => 'Todo', :visible => false)

但是,使用它会更容易 have_title 方法:

expect(page).to have_title('Todo')

16
2017-10-22 18:52



谢谢 - have_title 工作:)。我正在按照使用的教程 have_css 方法,对他们有效(在视频上),但也许是因为他们使用的是较旧版本的Caypbara,也许 has_css 已被弃用。我看到 have_title 未列入 Capybara匹配文档,就我所见,RSpec文档也没有,这让生活变得更加棘手,让人们对这些事情感到厌烦。 - Tim Jones
have_title 是在rdocs - 看 rubydoc.info/github/jnicklas/capybara/master/Capybara/...。 - Justin Ko
谢谢你的提醒 - 非常有帮助。我没有意识到RSpec有一个单独的匹配器部分 - 这不是一个明显的区别。虽然,看着文档,而 have_ 匹配器在那里,没有任何解释他们,这仍然使它很难! - Tim Jones
:visible => false 寻找作品 script 和 link 标签太:) - Brendon Muir