【发布时间】:2018-04-16 00:05:27
【问题描述】:
我正在尝试使用 Stripe API 测试我的 Rails 应用程序,所以我从模型开始,我正在使用 Rspec,我要测试的模型称为 bank_account.rb 里面有一个名为 (create_bank_account ) 带有参数 (bank_token) 它的伪代码是这样的:
def create_bank_account(bank_token)
# make a Stripe request and save it in local variable
# save needed data in my bank_account table in my DB
end
当我开始测试这个函数时,我发现里面有一个API调用,不好,我需要我的测试不依赖互联网,所以搜索后我找到了'StripeMock' gem,它很有用我开始将它与 Rspec 一起使用,但我发现自己正在编写这样的测试:
it 'with valid bank_token` do
# create a double for bank_account
# using StripeMock to get a faked response for creating
# new bank_account
# expect the doube to receive create_bank_account
# function and response with saving the data inside the DB
end
但在写完这篇文章后,我注意到我实际上并没有运行 create_bank_account 函数,我伪造了它,所以我的问题是:
1- 我如何测试包含 API 请求的函数但运行它自己而不是伪造的函数?
2- 我阅读了很多关于何时使用双精度和存根的信息,我的理解是当函数未完成时,但如果函数已经实现,我应该使用双精度来避免调用 API 之类的函数吗?
【问题讨论】:
-
您可以只使用 api 调用而不是函数本身的存根。例如说 api 调用由
Sendgrid.send()完成,然后你可以单独由Sendgrid.stub(:send).with('more_than', 'one_argument')存根。
标签: ruby-on-rails ruby testing stripe.net