I’m currently writing a web app that updates it’s pages CSS based on user input. I’ve got it all working fine, but I’m having trouble getting my automated tests to confirm that the CSS has actually been updated.
Basically, I just want to verify that the contents of a <style> tag in the document <head> have been updated to a certain value. I’m using capybara (with the selenium driver) for my tests, with this code:
styles = page.all('style')
styles.length.should == 1
styles[0].text.should == style
It all works as expected, until the final line, which fails as it seems that styles[0].text is always “”. I’ve also tried .value but it is always nil. I’m pretty sure the CSS is actually being updated, as I can see the changes in the firefox window that the tests are running in.
So, is there a way to get at the contents of the <style> tag using capybara?
It seems Capybara (with Selenium at least, I didn’t try any other drivers) won’t show you this, I presume because the style content is wrapped in an HTML comment so it gets ignored e.g.:
You do, however, have access to the page’s source with
page.source, so you can use that to get at the style content. The source is just a big string, so one way to dig into it is to parse it with Nokogiri (which is required by Capybara so you’ll have it already):If you’re asserting against customisable styles, and you’re using Selenium anyway, an alternative solution could involve using Javascript to determine the calculated style of an element, there seems to be no shortage of information on doing this. You could use Capybara’s
page.evaluate_scriptmethod to invoke a piece of Javascript that would tell you what a particular element actually looks like, and that may well be more robust than comparing the CSS text (e.g. if it gets minified by the app).