引发错误

使用 and_raise 使测试替身在接收消息时引发错误。 支持以下任何形式

* `and_raise(ExceptionClass)`
* `and_raise("message")`
* `and_raise(ExceptionClass, "message")`
* `and_raise(instance_of_an_exception_class)`

引发错误

给定一个名为“raises_an_error_spec.rb”的文件,其中包含

RSpec.describe "Making it raise an error" do
  it "raises the provided exception" do
    dbl = double
    allow(dbl).to receive(:foo).and_raise("boom")
    dbl.foo
  end
end

我运行 rspec raises_an_error_spec.rb

那么它应该失败,并显示

  1) Making it raise an error raises the provided exception
     Failure/Error: dbl.foo

     RuntimeError:
       boom