Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added an image matcher.

  • Loading branch information...
commit c75a15f8ea856a1ec631b9af808cc19183f14de4 1 parent 29084f6
bendycode authored
View
4 lib/html_matchers.rb
@@ -24,6 +24,10 @@ def have_dropdown target_id, expected_options
DropDownMatcher.new target_id, expected_options
end
+ def have_image expected_path
+ ImageMatcher.new expected_path
+ end
+
def have_options expected_options
OptionsMatcher.new expected_options
end
View
32 lib/matchers/image_matcher.rb
@@ -0,0 +1,32 @@
+module Spec # :nodoc:
+ module Rails
+ module Matchers
+ class ImageMatcher
+ def initialize expected_path
+ @expected = expected_path
+ end
+
+ def matches? response
+ @actual = extract_html_content response.body
+ @actual =~ /#{@expected}/
+ end
+
+ def failure_message
+ "\nWrong image path.\nexpected: #{@expected.inspect}\n found: #{@actual.inspect}\n\n"
+ end
+
+ def negative_failure_message
+ "\nShould not have matched image with path: '#{@expected}'\n\n"
+ end
+
+ def extract_html_content html
+ doc = Hpricot.XML(html)
+ elements = doc.search("img[@src*=\"#{@expected}\"]")
+ # elements.each {|e| puts e.inspect}
+ # elements.first.to_html
+ elements.map{|n| n.to_html}.first
+ end
+ end
+ end
+ end
+end
View
34 spec/image_matcher_spec.rb
@@ -0,0 +1,34 @@
+require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
+
+describe 'image_matcher' do
+ it 'should find matching image' do
+ response = mock_model(Object, :body => '<p><img id="image_id" src="/images/my_photo.jpg?1233455"/></p>')
+ response.should have_image('my_photo.jpg')
+ end
+
+ describe 'with non-matching expected' do
+ it 'should not match' do
+ response = mock_model(Object, :body => '<p><img id="image_id" src="/images/my_photo.jpg?1233455"/></p>')
+ response.should_not have_image('my_other_photo.gif')
+ end
+ end
+
+ describe 'with normal failure' do
+ it 'should raise ExpectationNotMetError with correct message' do
+ response = mock_model Object, :body => 'Some non-matching HTML'
+ lambda do
+ response.should have_image('my_photo.jpg')
+ end.should raise_error(Spec::Expectations::ExpectationNotMetError, "\nWrong image path.\nexpected: \"my_photo.jpg\"\n found: nil\n\n")
+ end
+ end
+
+ describe 'with negative failure' do
+ it 'should raise ExpectationNotMetError' do
+ response = mock_model Object, :body => '<p><img id="image_id" src="/images/my_photo.jpg?1233455"/></p>'
+ lambda do
+ response.should_not have_image('my_photo.jpg')
+ end.should raise_error(Spec::Expectations::ExpectationNotMetError,
+ "\nShould not have matched image with path: 'my_photo.jpg'\n\n")
+ end
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.