Ruby on rails 模拟rspec中的错误/异常(不仅仅是其类型)

Ruby on rails 模拟rspec中的错误/异常(不仅仅是其类型),ruby-on-rails,ruby,rspec,Ruby On Rails,Ruby,Rspec,我有这样一段代码: def some_method begin do_some_stuff rescue WWW::Mechanize::ResponseCodeError => e if e.response_code.to_i == 503 handle_the_situation end end end 如果e.response\u code.to\u I==503,我想测试部分中发生了什么。我可以模拟一些东西来抛出正确类型的异常:

我有这样一段代码:

def some_method
  begin
    do_some_stuff
  rescue WWW::Mechanize::ResponseCodeError => e
    if e.response_code.to_i == 503
      handle_the_situation
    end
  end
end
如果e.response\u code.to\u I==503,我想测试
部分中发生了什么。我可以模拟一些东西来抛出正确类型的异常:

whatever.should_receive(:do_some_stuff).and_raise(WWW::Mechanize::ResponseCodeError)
但是,当错误对象接收到“response\u code”时,我如何模拟它本身以返回503呢?

现在RSpec附带了它来确保你的模拟对象符合真实对象的API(即它的可用方法/方法调用)

要求“机械化”
福班
定义某些方法
开始
做点什么
救援WWW::Mechanize::ResponseCodeError=>e
如果e.response_code.to_i==503
处理情况
结束
结束
结束
结束
RSpec.description Foo do
主题(:foo){descripted_class.new}
描述“#一些#u方法”做什么
主题{foo.some_method}
let(:mechanize_error){instance_double(WWW::mechanize::responsecode:'503')}
在{expect(foo).接收(:do_some_stuff.)和{u raise(mechanize_error)}
它“处理503响应”do
expect(foo).to receive(:handle_the_情境)#将调用断言错误处理程序
主题
结束
结束
结束
我试着尽可能清晰、干净地编写测试,因为代码被计算机读取一次,但被人类(您的同事/团队成员)读取数百次

require 'mechanize'

class Foo

  def some_method
    begin
      do_some_stuff
    rescue WWW::Mechanize::ResponseCodeError => e
      if e.response_code.to_i == 503
        handle_the_situation
      end
    end
  end

end

describe "Foo" do

  it "should handle a 503 response" do
    page = stub(:code=>503)
    foo = Foo.new
    foo.should_receive(:do_some_stuff).with(no_args)\
    .and_raise(WWW::Mechanize::ResponseCodeError.new(page))
    foo.should_receive(:handle_the_situation).with(no_args)
    foo.some_method
  end

end