Capybara/RSpec'have_css'匹配器不工作但has_css没有

Tim*_*nes 11 rspec capybara ruby-on-rails-3.2

在使用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
Run Code Online (Sandbox Code Playgroud)

失败消息是:

 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.
Run Code Online (Sandbox Code Playgroud)

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

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

expect(page).to have_css('title', text: "Todo")
Run Code Online (Sandbox Code Playgroud)

对此:

page.has_css?('title', text: "Todo")
Run Code Online (Sandbox Code Playgroud)

然后测试通过.[编辑 - 但请看@JustinKo下面的回复,这个测试不是一个好的测试,因为它总是会通过]

如何让have_css(...)表单生效?这是配置问题吗?

这是我的相关部分Gemfile:

group :development, :test do
  gem 'rspec-rails' 
  gem 'capybara'
end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

Jus*_* Ko 16

默认情况下,Capybara只查找"可见"元素.头元素(及其标题元素)实际上并不可见.这导致在have_css中忽略title元素.

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

expect(page).to have_css('title', :text => 'Todo', :visible => false)
Run Code Online (Sandbox Code Playgroud)

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

expect(page).to have_title('Todo')
Run Code Online (Sandbox Code Playgroud)