Rspec模拟错误:参数数量错误

Lan*_*opp 14 ruby rspec stripe-payments

我正在尝试使用Rspec来删除Stripe API,我遇到了一个问题.这是我的代码的样子:

Stripe::Customer.should_receive(:create).with(any_args).and_raise(Stripe::CardError)
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

Failure/Error: Stripe::Customer.should_receive(:create).with(any_args).and_raise(Stripe::CardError)
ArgumentError:
  wrong number of arguments (0 for 3..6)
Run Code Online (Sandbox Code Playgroud)

Pet*_*vin 20

根据以下源代码,Stripe :: CardError需要3..6个参数:

class CardError < StripeError
  ...
  def initialize(message, param, code, http_status=nil, http_body=nil, json_body=nil)
Run Code Online (Sandbox Code Playgroud)

以下是github上RSpec doc的关键文档:

expect(double).to receive(:msg).and_raise(error)
  #error can be an instantiated object or a class
  #if it is a class, it must be instantiable with no args
Run Code Online (Sandbox Code Playgroud)

因为你只是提供类和类需要参数,所以它失败了.您需要实例化它(即通过new)并提供参数.

完整定义在https://github.com/stripe/stripe-ruby/blob/0c281891948a793e79cc997d31918ba7f987f7ae/lib/stripe/errors/card_error.rb

  • 这个答案帮助我发现我写不出像'expect(obj).to receive(:msg).and_raise(ActiveRecord :: RecordInvalid)`.我必须将记录传递给错误.`expect(obj).to receive(:msg).and_raise(ActiveRecord :: RecordInvalid.new(obj))`.从RSpec返回的"ArgumentError:错误的参数个数(0表示1)"的堆栈跟踪和消息没有明显表明错误消息未正确初始化.谢谢您的帮助! (8认同)