xoail
xoail

Reputation: 3064

Capture and assert Meta tags in RSpec

I am trying to write a unit test to assert few meta tag values (under section of the response). How can I use the attribute tag to check individual value? Ex:

<meta property="keyword" content="site keywords" />
<meta property="description" content="site description" />

So far this is all I got. But it comes back as failed.

it "should check meta fields" do
  get :show, {:format => 'html' }
  r = response.body
  r.should have_selector('meta', :content => @site.title)
end

Upvotes: 3

Views: 2674

Answers (2)

Artur INTECH
Artur INTECH

Reputation: 7266

To assert <meta> tag:

have_selector 'meta[property=keyword][content="site keywords"]', visible: false

For <title> Capybara has a built-in matcher:

have_title 'The title of my website'

Upvotes: 2

Chris Salzberg
Chris Salzberg

Reputation: 27374

Capybara's have_selector matcher takes an option :text, not :content:

r.should have_selector('meta', :text => @site.title)

See this discussion and this discussion on github.

However, that doesn't explain why your spec fails, since the :content option is ignored and should make your test if anything more permissive.

The most likely reason this test is failing is that it is being called from a controller spec, in which case the response will be blank because rspec-rails prevents rails from actually rendering views. If this is the case, you will need to either move the spec to a file under spec/requests/, or add the directive render_views just inside the describe block.

If that doesn't work then you'll have to provide more information on the context for the spec, otherwise it's hard to figure out what's going wrong.

Upvotes: 4

Related Questions