Skip to content

Instantly share code, notes, and snippets.

@lucasmarqs
Last active January 11, 2016 21:07
Show Gist options
  • Save lucasmarqs/5dee201f844bc90f8545 to your computer and use it in GitHub Desktop.
Save lucasmarqs/5dee201f844bc90f8545 to your computer and use it in GitHub Desktop.
Rspec :have_tag matcher
require 'rspec/expectations'
RSpec::Matchers.define :have_tag do |html_tag|
match do |html_string|
@doc = Nokogiri::HTML.fragment(html_string)
@html_tag = html_tag
if @class_names.nil? && @content.nil?
have_html_tag?(html_tag)
elsif @class_names && @content.nil?
have_html_tag?(html_tag) && have_class_name?(html_tag)
elsif @content
have_html_tag?(html_tag) && have_content?(html_tag)
end
end
chain :with_class do |class_names|
@class_names = class_names
end
chain :with_content do |content|
@content = content
end
def have_html_tag?(html_tag)
@doc.search(html_tag).any?
end
def have_class_name?(html_tag)
doc_class_names = @doc.at(html_tag).attributes['class'].value.split(' ').sort
doc_class_names.include?(@class_names) || doc_class_names == @class_names.split(' ').sort
end
def have_content?(html_tag)
@doc.at(html_tag).text.strip == @content.strip
end
end
RSpec.describe "<p class='style fa'>Teste</p>" do
it { is_expected.to have_tag('p') } # should pass
it { is_expected.to_not have_tag('a') } # should pass
it { is_expected.to have_tag('p').with_class('style') } # should pass
it { is_expected.to have_tag('p').with_class('fa stas')} # should fail
it { is_expected.to have_tag('p').with_content('Teste') } # should pass
it { is_expected.to have_tag('p').with_content('Teste1') } # should fail
end
RSpec::Matchers.define :have_class_name_at do |class_name, html_tag|
match do |html_string|
doc = Nokogiri::HTML.fragment(html_string)
class_names = doc.at(html_tag).attributes['class'].value.split(' ')
class_names.include?(class_name)
end
end
RSpec::Matchers.define :have_content_at do |content, html_tag|
match do |html_string|
doc = Nokogiri::HTML.fragment(html_string)
doc.at(html_tag).text.strip == content.strip
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment