水豚/ RSpec的“have_css”匹配不工作,但has_css确实
在使用Ruby 2一个Rails应用程序3.2.14使用RSpec的护栏2.14.0和水豚2.1.0以下特点规范导致了失败:水豚/ RSpec的“have_css”匹配不工作,但has_css确实
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.
title元素和正确的文本是所呈现的页面
上但是,当我改变这一行的功能规格:
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
任何人都知道我可能是做错了什么?
默认情况下,水豚只会查找“可见”元素。头元素(及其标题元素)并不真正被视为可见。这导致标题元素在has_css中被忽略。
您可以强制Capybara也考虑:visible => false
选项的不可见元素。
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](http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Matchers)中,也没有在RSpec文档中列出我可以看到,这让生活变得有点棘手,把这些事情作为新任务的人来处理。 –
'have_title'在rdocs中 - 请参阅http:// rubydoc。信息/ github上/ jnicklas /豚/主/水豚/ RSpecMatchers。 –
感谢您的领导 - 真的很有帮助。我没有意识到RSpec有一个单独的匹配器部分 - 这不是一个明显的区别。虽然看着这些文档,虽然在那里有'have_'匹配器,但是没有任何解释反对它们,这仍然很难! –
请继续前进,看到这篇文章,尤其是水豚部分http://nofail.de/2013/10/debugging -rails-applications-in-development/ – phoet
如果你只是做了'page.has_css?('title',text:'Todo')',测试总是会通过。 'has_css?'只是返回true或false,这不足以使测试失败。如果你输出它,你可能会看到它是错误的。你确定页面有一个标题元素和文本? –
@JustinKo感谢您指出新手错误。是的,标题显示了适当的文字 - 在浏览器中检查。 –