2013-06-25 86 views
12

我试图使用Rspec来刷出Stripe API,并且遇到问题。这里是我的代码如下所示:Rspec mocks错误:参数数量错误

Stripe::Customer.should_receive(:create).with(any_args).and_raise(Stripe::CardError) 

这里是我得到的错误:

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

是否Stripe :: CardError需要3..6个参数? –

+0

我认为它可能,但我在印象之下Rspec会做一个小小的魔术来创建一个模拟错误的实例。情况并非如此吗? – LandonSchropp

+0

我没有意识到这种能力,但它无论如何都没有机会,因为在RSpec有机会做任何事情之前,Ruby会评估Strip :: CardError。 –

回答

19

条纹:: CardError需要3..6参数,按照下面的源代码:

class CardError < StripeError 
    ... 
    def initialize(message, param, code, http_status=nil, http_body=nil, json_body=nil) 

下面是从RSpec的文档在GitHub上的重要文件:

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 

由于您只是提供了类,而且类需要参数,因此失败了。您需要实例化它(即通过new)并提供参数。

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

+0

够简单。谢谢您的帮助。 – LandonSchropp

+5

这个答案帮助我发现我不能写'expect(obj).to接收(:msg).and_raise(ActiveRecord :: RecordInvalid)''。我必须将记录传递给错误。 'expect(obj).to接收(:msg).and_raise(ActiveRecord :: RecordInvalid.new(obj))''。从'ArgumentError:参数的错误数量(0代表1)'的RSpec返回的堆栈跟踪和消息并未明显表明错误消息未被正确初始化。谢谢您的帮助! –

+1

@KyleTolle谢谢你。自午餐后,我一直对此感到震惊。 –