水豚/RSpec&x27;拥有css';matcher不工作,但有

水豚/RSpec&x27;拥有css';matcher不工作,但有,rspec,ruby-on-rails-3.2,capybara,Rspec,Ruby On Rails 3.2,Capybara,在使用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")

在使用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的回复,该测试不是一个好的测试,因为它将始终通过]

我如何让
有css(…)
表单工作?这是配置问题吗?

以下是我的
Gemfile
的相关部分:

group :development, :test do
  gem 'rspec-rails' 
  gem 'capybara'
end
我的
spec/spec\u 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

有人知道我可能做错了什么吗?

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


您可以强制Capybara也通过代码>考虑不可见元素:Visual= > false 选项.< /P>
expect(page).to have_css('title', :text => 'Todo', :visible => false)
但是,使用
have_title
方法更容易:

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

请继续阅读这篇文章,特别是水豚部分,如果你只做
页面。有css?('title',文本:“Todo”)
,测试总是会通过的
has_css?
只返回true或false,这不足以使测试失败。如果您输出它,您可能会看到它是假的。你确定页面上有一个带有文本的标题元素吗?@JustinKo感谢你指出了新手的错误。是的,标题显示时已在浏览器中选中相应的文本。是否确定它是“title”元素而不是“H2”或“H3”?谢谢-
have\u title
works:)。我在学习一个教程,该教程使用了
have_css
方法,该方法对他们有效(在视频中),但可能是因为他们使用的是Caypbara的旧版本,并且可能
has_css
已被弃用。据我所知,
have_title
没有在中列出,也没有在RSpec文档中列出,这使得生活变得有点棘手,作为一个新任务的人,了解这些事情。
have_title
在rdocs中-请参阅。感谢大家的提醒-非常有用。我不知道RSpec有一个单独的matchers部分——这不是一个明显的区别。虽然,看看这些文档,虽然
有匹配者在那里,但没有人对它们有任何解释,这仍然让它很难<代码>:visible=>false
用于查找
script
link
标记:)