Working on a project this weekend, I found that i needed to tell if a page was not found (404 Error) and then do something based off that. I was writing specs and trying to figure out how to stub a Mechanize object to return a 404. It turns out that anything except a 200 (OK), 301 (Moved Permanently) and 302 (Found, Redirect) will raise an exception. Specifically a WWW::Mechanize::ResponseCodeError.
RSpec conveniently gives us a way to say that a method will raise an exception when it is called. and_raise(ExceptionClass). Trying this out myself, I kept getting back
wrong number of arguments (0 for 1)
and I didn’t understand why. I came across a posting to the rspec-users mailing list that said that what i was doing (
agent.stub(:get).with(some_url).and_raise(WWW::Mechanize::ResponseCodeError)
wasn’t quite right. Many exception classes, it turns out, take an argument when they are raised. So I tried
agent.stub(:get).with(some_url).and_raise(WWW::Mechanize::ResponseCodeError(agent))
and that still didn’t work, as agent didn’t respond to :code. A little bit of stubbing later, and agent responds to code (returned a “400″) and now it works like a charm.
Add your comment below, or trackback from your own site.
Subscribe to these comments.
Be nice. Keep it clean. Stay on topic. No spam.
You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>