微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Capybara / RSpec’has_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看到这个测试不是一个很好的测试,因为它总是会通过]

如何获得has_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

任何人知道我可能做错了什么?

解决方法

认情况下,Capybara仅查找“可见”元素.头元素(及其标题元素)并不真正被视为可见.这导致在has_css中标题元素被忽略.

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

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

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

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

原文地址:https://www.jb51.cc/css/214506.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。