【发布时间】:2015-07-14 21:02:09
【问题描述】:
在我的 Ruby(不是 Rails)程序中,我在顶层模块中创建了全局变量。这些全局变量被设置为外部服务的客户端,所以我的程序在设置它们时会进行 API 调用。我试图弄清楚如何在 RSpec 中正确地存根这些 API 调用。
我想测试顶部模块中的一个类,它看起来或多或少像这样。 Worker 不会直接调用类中任何地方的全局变量。
module TopModule
class Worker
end
end
这是 TopModule:
module TopModule
# (As an aside, the external service is AWS)
$client = ExternalService::Client.new(ExternalService.config)
end
我想运行 TopModule::Worker 的 RSpec 测试,让它通过:
describe TopModule::Worker do
it 'shows in various ways that Worker functions'
end
但是,我收到以下错误:Real HTTP connections are disabled. Unregistered request: GET http://... with headers {...} (WebMock::NetConnectNotAllowedError)
堆栈跟踪指向 TopModule 中定义 $client 的行。
我也被告知:
You can stub this request with the following snippet:
stub_request(:get, "http://...").
with(:headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'...', 'User-Agent'=>'Ruby'}).
to_return(:status => 200, :body => "", :headers => {})
当我将存根添加到我的 spec/spec_helper RSpec.configure 循环时,我仍然遇到错误。以下是 spec_helper 的相关部分:
require 'webmock/rspec'
require 'codeclimate-test-reporter'
WebMock.disable_net_connect!(allow: 'codeclimate.com')
require 'fileutils'
require 'top_module'
Dir['./spec/support/**/*.rb'].sort.each { |f| require f }
RSpec.configure do |config|
config.mock_with :rspec do |mocks|
mocks.verify_doubled_constant_names = true
mocks.verify_partial_doubles = true
end
end
def files_directory
File.dirname(__FILE__) + '/files'
end
我可以将存根放在哪里,以便它实际处理 ExternalService API 调用?非常感谢您的帮助。
(此代码基于我的真实代码,但不完全相同)
【问题讨论】:
标签: global-variables stub ruby-2.0 rspec3