Matt Gibson
Matt Gibson

Reputation: 14949

How can I check that a HTML fragment is valid using Rspec?

Say I have a view helper that outputs something like this as a string:

'<div class="tag"><a href="posts/tagname"Tagname</a></div>'

How can I do something like this in Rspec?

the_string.should be_valid_html

I have looked at be_valid_asset, but it requires a network connection to hit the W3C servers and this really isn't necessary (plus it mangles the CI server). All I need is to make sure it isn't missing an angle bracket or something. Regexp seems like the wrong solution for parsing HTML (yes, I've seen that answer).

Upvotes: 3

Views: 800

Answers (2)

Billy Chan
Billy Chan

Reputation: 24815

Not a direct answer but I don't think it's necessary to write tests for such details in view. Too much tests to write otherwise.

If all you need to is to ensure no missing bracket, I would suggest you to use Haml or Slim for templating. Any errors will be thrown and you don't even have a chance to write brackets in most cases.

Upvotes: 0

Rebitzele
Rebitzele

Reputation: 3282

Although I haven't used it, here's a gem that claims to do what you're looking for:

https://github.com/ericbeland/html_validation

Upvotes: 1

Related Questions