gpt4 book ai didi

ruby - 根据要求使用特定的 VCR 磁带

转载 作者:数据小太阳 更新时间:2023-10-29 07:10:25 27 4
gpt4 key购买 nike

情况:使用 Rspec、FactoryGirl 和 VCR 测试 Rails 应用程序。

每次创建用户时,都会通过 Stripe 的 API 创建关联的 Stripe 客户。测试时,添加 VCR.use_cassettedescribe "...", vcr: {cassette_name: 'stripe-customer'} do ... 到涉及用户创建的每个规范。我的实际解决方案如下:

RSpec.configure do |config|
config.around do |example|
VCR.use_cassette('stripe-customer') do |cassette|
example.run
end
end
end

但这是不可持续的,因为每个 http 请求都会使用同一个盒式磁带,这当然是非常糟糕的。

问题如何根据个人要求使用特定的夹具(暗盒),而不是为每个规范指定暗盒?

我有这样的想法,伪代码:

stub_request(:post, "api.stripe.com/customers").with(File.read("cassettes/stripe-customer"))

相关代码片段(作为 gist ):

# user_observer.rb

class UserObserver < ActiveRecord::Observer

def after_create(user)
user.create_profile!

begin
customer = Stripe::Customer.create(
email: user.email,
plan: 'default'
)

user.stripe_customer_id = customer.id
user.save!
rescue Stripe::InvalidRequestError => e
raise e
end

end
end


# vcr.rb

require 'vcr'

VCR.configure do |config|
config.default_cassette_options = { record: :once, re_record_interval: 1.day }
config.cassette_library_dir = 'spec/fixtures/cassettes'
config.hook_into :webmock
config.configure_rspec_metadata!
end


# user_spec.rb

describe :InstanceMethods do
let(:user) { FactoryGirl.create(:user) }

describe "#flexible_name" do
it "returns the name when name is specified" do
user.profile.first_name = "Foo"
user.profile.last_name = "Bar"

user.flexible_name.should eq("Foo Bar")
end
end
end

编辑

我结束了这样的事情:

VCR.configure do |vcr|
vcr.around_http_request do |request|

if request.uri =~ /api.stripe.com/
uri = URI(request.uri)
name = "#{[uri.host, uri.path, request.method].join('/')}"
VCR.use_cassette(name, &request)

elsif request.uri =~ /twitter.com/
VCR.use_cassette('twitter', &request)
else
end

end
end

最佳答案

VCR 2.x 包含专门用于支持此类用例的功能:

https://relishapp.com/vcr/vcr/v/2-4-0/docs/hooks/before-http-request-hook ! https://relishapp.com/vcr/vcr/v/2-4-0/docs/hooks/after-http-request-hook ! https://relishapp.com/vcr/vcr/v/2-4-0/docs/hooks/around-http-request-hook !

VCR.configure do |vcr|
vcr.around_http_request(lambda { |req| req.uri =~ /api.stripe.com/ }) do |request|
VCR.use_cassette(request.uri, &request)
end
end

关于ruby - 根据要求使用特定的 VCR 磁带,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16533980/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com