23

Capybara 2.1.0 似乎没有找到任何元标记:

(rdb:1) p page.find 'meta'
*** Capybara::ElementNotFound Exception: Unable to find css "meta"

即使它们出现在page.source

(rdb:1) p page.source
"<!doctype html>\n<html>\n<head>\n<title>MyTitle</title>\n<meta charset='utf-8'>\n<meta content='IE=edge,chrome=1' http-equiv='X-UA-Compatible'>\n<meta content='width=device-width, initial-scale=1' name='viewport'>\n<meta name='description'>\n\n..."
4

3 回答 3

41

解决方案是使用:visible => falseinfind或 in have_selector

page.should have_css 'meta[name="description"]', visible: false

或者:

page.find 'meta[name="description"]', visible: false
于 2013-04-17T23:51:59.083 回答
10

如果您想查看更具体的元数据,包括描述文本等:

https://gist.github.com/Lordnibbler/6247531

RSpec::Matchers.define :have_meta do |name, expected|
  match do |actual|
    has_css?("meta[name='#{name}'][content='#{expected}']")
  end

  failure_message_for_should do |actual|
    actual = first("meta[name='#{name}']")
    if actual
      "expected that meta #{name} would have content='#{expected}' but was '#{actual[:content]}'"
    else
      "expected that meta #{name} would exist with content='#{expected}'"
    end
  end
end

RSpec::Matchers.define :have_title do |expected|
  match do |actual|
    has_css?("title", :text => expected)
  end

  failure_message_for_should do |actual|
    actual = first("title")
    if actual
      "expected that title would have been '#{expected}' but was '#{actual.text}'"
    else
      "expected that title would exist with '#{expected}'"
    end
  end
end

然后,像这样查找元数据:

page.should have_meta(:description, 'Brand new Ruby on Rails TShirts')

从 Spree 借来的爱:https ://github.com/spree/spree/blob/master/core/lib/spree/testing_support/capybara_ext.rb

于 2013-08-16T05:29:18.183 回答
1

提议的解决方案在 2021 年不起作用,但以下解决方案确实有效

page.find('//head/meta[name="description"]', visible: false)[:content]

根据https://rubydoc.info/github/jnicklas/capybara/Capybara/Node/Element

Element 还可以访问 HTML 属性和元素的其他属性:

bar.value bar.text bar[:title]

于 2021-06-03T05:28:42.797 回答