【问题标题】:Capybara/RSpec 'have_css' matcher not working but has_css doesCapybara/RSpec 'have_css' 匹配器不工作,但 has_css 可以
【发布时间】:2013-10-31 10:33:32
【问题描述】:

在带有 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

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

【问题讨论】:

  • 请继续阅读这篇文章,尤其是水豚部分nofail.de/2013/10/debugging-rails-applications-in-development
  • 如果你只做page.has_css?('title', text: "Todo"),测试总会通过。 has_css? 仅返回 true 或 false,这不足以使测试失败。如果你输出它,你可能会看到它是假的。您确定该页面有一个带有文本的标题元素吗?
  • @JustinKo 感谢您指出新手错误。是的,标题与适当的文本一起显示 - 在浏览器中选中。
  • 你确定是 'title' 元素而不是 'H2' 或 'H3'?

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


【解决方案1】:

默认情况下,Capybara 只查找“可见”元素。头元素(及其标题元素)实际上并不被认为是可见的。这会导致在 have_css 中忽略 title 元素。

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

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

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

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

【讨论】:

  • 谢谢 - have_title 工作:)。我正在关注一个使用 have_css 方法的教程,该方法对他们有用(在视频中),但可能是因为他们使用的是旧版本的 Caypbara,并且可能 has_css 已被弃用。我看到have_title 没有列在Capybara matchers documentation 中,也没有列在RSpec 文档中,据我所知,这使得作为一个新人来处理这些事情变得有点棘手。跨度>
  • have_title 在 rdocs 中 - 请参阅 rubydoc.info/github/jnicklas/capybara/master/Capybara/…
  • 感谢您的提醒 - 真的很有帮助。我没有意识到 RSpec 有一个单独的匹配器部分 - 这不是一个明显的区别。尽管查看文档,虽然 have_ 匹配器在那里,但没有人对它们有任何解释,这仍然很难!
  • :visible => false 也可用于查找 scriptlink 标签 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-26
  • 2015-01-16
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多