Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capybara not finding meta tags

Capybara 2.1.0 doesn't seem to find any meta tags:

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

even when they appear in 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..."
like image 608
alf Avatar asked Apr 17 '13 23:04

alf


3 Answers

The solution was to use :visible => false either in find or in have_selector:

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

or:

page.find 'meta[name="description"]', visible: false
like image 50
alf Avatar answered Oct 15 '22 00:10

alf


If you want to check more specific meta, including the description text, etc:

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

Then, look up meta like so:

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

Borrowed with love from Spree: https://github.com/spree/spree/blob/master/core/lib/spree/testing_support/capybara_ext.rb

like image 39
professormeowingtons Avatar answered Oct 15 '22 01:10

professormeowingtons


The proposed solution did not work in 2021, but the following did

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

According to https://rubydoc.info/github/jnicklas/capybara/Capybara/Node/Element

Element also has access to HTML attributes and other properties of the element:

bar.value bar.text bar[:title]

like image 1
sorenwiz Avatar answered Oct 15 '22 00:10

sorenwiz