0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

raise_errorマッチャー

Last updated at Posted at 2025-01-03

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_errorraise_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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?