kucaahbe / rspec-html-matchers

Old school have_tag, with_tag(and more) matchers for rspec 3 (Nokogiri powered)
http://rubygems.org/gems/rspec-html-matchers
MIT License
199 stars 90 forks source link
rspec ruby testing

rspec-html-matchers Gem Version

RSpec matchers for testing your html (for RSpec 2 use 0.5.x version).

RSpec MRI RSpec JRuby Cucumber MRI

Goals

Install

Add to your Gemfile in the :test group:

gem 'rspec-html-matchers'

Include it in your RSpec configuration:

RSpec.configure do |config|
  config.include RSpecHtmlMatchers
end

or just in your spec(s):

describe "my view spec" do
  include RSpecHtmlMatchers

  it "has tags" do
    expect(rendered).to have_tag('div')
  end
end

Cucumber configuration:

World RSpecHtmlMatchers

as this gem requires nokogiri, here are instructions for installing it.

Usage

so perhaps your code produces following output:

<h1>Simple Form</h1>
<form action="/users" method="post">
<p>
  <input type="email" name="user[email]" />
</p>
<p>
  <input type="submit" id="special_submit" />
</p>
</form>

so you test it with the following:

expect(rendered).to have_tag('form', :with => { :action => '/users', :method => 'post' }) do
  with_tag "input", :with => { :name => "user[email]", :type => 'email' }
  with_tag "input#special_submit", :count => 1
  without_tag "h1", :text => 'unneeded tag'
  without_tag "p",  :text => /content/i
end

Example above should be self-descriptive, if not, please refer to the have_tag documentation

Input can be any html string. Let's take a look at these examples:

where page is an instance of Capybara::Session

and of course you can use the without_ matchers, for more info take a look at documentation

rspec 1 partial backwards compatibility:

you can match:

expect(response).to have_tag('div', 'expected content')
expect(response).to have_tag('div', /regexp matching expected content/)

RSpec 1 have_tag documentation

Matching Tag Attributes

You can also match the content of attributes by using selectors. For example, to ensure an img tag has an alt attribute, you can match:

expect(index).to have_tag("img[alt!='']")

More info

You can find more on documentation

Also, please read CHANGELOG and issues, might be helpful.

Contribution

  1. Fork the repository
  2. Add tests for your feature
  3. Write the code
  4. Add documentation for your contribution
  5. Send a pull request

Contributors