Forum: RSpec how to catch a missing image (rspec-rails)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D290fac88e465402a18d97946a968911?d=identicon&s=25 Evan Dorn (idahoev)
on 2008-10-03 05:43
I want to make sure all external resources called for by my views (like
images) actually exist.  How do I write an rspec that will fail when an
image included on the page isn't present?


For example, let's say in application.html.erb, I include <img
src="/images/mylogo.png">, but that file doesn't exist (say it's
actually /images/mylogo.jpg).

When this is run on the server, the image won't appear, and the server
log will show an error like this:

 >> ActionController::RoutingError (No route matches
"/images/mylogo.png" with
 >> {:method=>:get}):

However, views tests like response.should have_tag(img[src=/mylogo.png/)
won't catch it, because the tag will be there.    controllers tests
(with integrate_views on) for response.should be_success,
render_template won't catch it because the page itself was a success and
rendered the template.

But an error was thrown during a second connection to the server,
because the image file didn't exist ... there must be a way for any such
failures.  How?

Thanks!
Ev
42172acdf3c6046f84d644cb0b94642c?d=identicon&s=25 Pat Maddox (pergesu)
on 2008-10-03 07:37
(Received via mailing list)
Evan Dorn <lists@ruby-forum.com> writes:

> log will show an error like this:
>
> But an error was thrown during a second connection to the server,
> because the image file didn't exist ... there must be a way for any such
> failures.  How?

Hi Evan,

Can you rely on the convention that images are under RAILS_ROOT/public?
If so, you could do a little translucent-box testing.  Maybe you could
use hpricot to get all the image elements and check their referenced
file's existence.

# I'm just BSing the hpricot
hpricot("doc/img") do |element|
  element.attr('src').should be_existing_resource
end

Where be_existing_resource is a custom matcher with a simple
implementation of

def matches?(actual)
  File.exists?(File.expand_path(RAILS_ROOT + actual))
end

(simple enough for a simple matcher, even)

This should give you a good deal of confidence without any hassle.

Pat
This topic is locked and can not be replied to.