rails Rspec mock/stabのやり方

本稿について

本稿はサイト運営者が学んだことなどを記したメモの内容です。
全てが正確な情報とは限りません。ご注意ください。また修正するべき点は適時修正していきます

mockを利用してexceptionを発生させる
allow(Hoge).to receive(:fuga).and_raise(‘error’)


instance_doubleを使えば以下のような複雑なインスタンスも作れる
@subscription_mock = instance_double('StripeSubscriptionMock',
  id: "subscription_id",
  status: "active",
  current_period_start: 1595145133,
  current_period_end: 1598145133,
  plan: instance_double("Stripe Plan Mock", name: “Stripe Hoge"),
      discount: instance_double("Stripe Discount Mock",
        coupon: instance_double("StripeCouponMock", name: “hoge")
      )
  )

  allow(Stripe::Subscription).to receive(:create).and_return(@subscription_mock)



setterのmock
http_mock = instance_double('HTTP mock')
allow(http_mock).to receive(:use_ssl=).and_return(true)
allow(http_mock).to receive(:verify_mode=).and_return(OpenSSL::SSL::VERIFY_NONE)

[参考]


メソッド名
検証内容
once
1 回だけ
twice
きっちり 2 回
exactly(n).times
きっちり n 回
at_least(:once)
1 回以上(デフォルト)
at_least(:twice)
2 回以上
at_least(n).times
n 回以上
at_most(:once)
0 または 1 回
at_most(:twice)
2 回以下
at_most(n).times
n 回以下

[参考]

引数を含めて動作を検証する場合はwithをつける
allow(egg_user_mock).to receive(:is_canceled_user?).with(‘hoge').and_return(false)

Back