在rspec中模拟错误/异常(不仅仅是它的类型)

时间:2021-05-24 23:30:44

I have a block of code like this:

我有一个像这样的代码块:

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

I want to test what's going on in that if e.response_code.to_i == 503 section. I can mock do_some_stuff to throw the right type of exception:

如果e.response_code.to_i == 503部分,我想测试一下发生了什么。我可以模拟do_some_stuff来抛出正确的异常类型:

whatever.should_receive(:do_some_stuff).and_raise(WWW::Mechanize::ResponseCodeError)

but how do I mock the error object itself to return 503 when it receives "response_code"?

但是当我收到“response_code”时,如何模拟错误对象本身返回503?

1 个解决方案

#1


21  

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

#1


21  

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