raise_error
マッチャー
raise_error matcher
エラーを起こすコードのブロックを明示するためにraise_error
マッチャーを使う。最も基本形はどんなエラーが投げられても通ります
Use the raise_error matcher to specify that a block of code raises an error. The most basic form passes if any error is thrown:
expect { raise StandardError }.to raise_error
その言葉づかいの方を好むならば代わりとしてraise_exception
を使える
You can use raise_exception instead if you prefer that wording:
expect { 3 / 0 }.to raise_exception
raise_error
とraise_exception
は機能的に互換性があるのでどのようなコンテキストでも最も意味のある方を使う
raise_error and raise_exception are functionally interchangeable, so use the one that makes the most sense to you in any given context.
上記の基本形に加えて、エラー・例外の詳細を明示するための方法のいくつかある
In addition to the basic form, above, there are a number of ways to specify details of an error/exception:
expect { raise "oops" }.to raise_error
expect { raise "oops" }.to raise_error(RuntimeError)
expect { raise "oops" }.to raise_error("oops")
expect { raise "oops" }.to raise_error(/op/)
expect { raise "oops" }.to raise_error(RuntimeError, "oops")
expect { raise "oops" }.to raise_error(RuntimeError, /op/)
expect { raise "oops" }.to raise_error(an_instance_of(RuntimeError).and having_attributes(message: "oops"))
どんなエラーも期待する
Expecting any error
RSpec.describe "calling a missing method" do
it "raises" do
expect { Object.new.foo }.to raise_error # 定義されていないメソッドを使用によってエラーが起こると考える
end
end
Run options: include {:full_description=>/calling\ a\ missing\ method/}
WARNING: Using the `raise_error` matcher without providing a specific error or message risks false positives, since `raise_error` will match when Ruby raises a `NoMethodError`, `NameError` or `ArgumentError`, potentially allowing the expectation to pass without even executing the method you are intending to call. Actual error raised was #<NoMethodError: undefined method `foo' for #<Object:0x000000010d928818>>. Instead consider providing a specific error class or message. This message can be suppressed by setting: `RSpec::Expectations.configuration.on_potential_false_positives = :nothing`. Called from /Users/hyoudoumasatomo/Repos/garden/spec/models/user_spec.rb:17:in `block (2 levels) in <top (required)>'.
1 example, 0 failures, 1 passed