Ramon Tayag
Ramon Tayag

Reputation: 16084

Capybara: How to test a stylesheet of a page?

I want to have the ability to test the correct swapping of a stylesheet in my test suite. With this post about testing the page title using Capybara, I thought I would be able to test any link tags in the head section of the page. But it seems I am mistaken.

With a step like this:

save_and_open_page
page.should have_xpath("//link") # just something as simple as this, first.

save_and_open_page generates a HTML like this (with some stuff removed for brevity):

<head>
  ...
  <link href="/home/ramon/source/unstilted/public/system_test/stylesheets/fancake/css/2.css?1323572998" type="text/css" class="jquery-styler" rel="stylesheet">
  ...
</head>

But I get this failure:

expected xpath "//link" to return something (RSpec::Expectations::ExpectationNotMetError)

Given all that, how do I test a stylesheet?

Thanks!

Upvotes: 5

Views: 1659

Answers (2)

MZaragoza
MZaragoza

Reputation: 10111

When I am checking for a css what I do is something like

expect(page.body).to include('/home/ramon/source/unstilted/public/system_test/stylesheets/fancake/css/2.css')

Upvotes: 1

Sam Starling
Sam Starling

Reputation: 5378

If you want to check that a CSS file exists on a page, then you can do the following:

page.should have_xpath("//link[contains(@href, 'style.css')]")

That'll check whether there are any <link> elements where the href attribute contains style.css. The error about "expected xpath to return something" means that the XPath you provided didn't actually exist - why it thinks that, I'm not sure, as you have a perfectly valid <link> tag in the HTML you've provided.

Upvotes: 4

Related Questions