我如何在全局范围内 stub 一个 http 请求,例如下面的 twitter api,以便它对 Test::Unit 套件中的所有测试有效?
stub_request(:get, "https://api.twitter.com/1/users/show.json?screen_name=digiberber").
with(:headers => {'Accept'=>'application/json', 'User-Agent'=>'Twitter Ruby Gem 1.1.2'}).
to_return(:status => 200, :body => "", :headers => {})
这WebMock stub 在 TestCase 子类的 setup() block 中工作,例如
class MyTest < ActiveSupport::TestCase
setup do
stub_request(...)...
end
end
但如果我将它放在 TestCase 本身的全局设置中,则不会被识别:
require 'webmock/test_unit'
class ActiveSupport::TestCase
setup do
stub_request(...)
end
end
这给了我错误:
NoMethodError: undefined method `stub_request' for ActiveSupport::TestCase:Class
我也尝试过修补方法 def 本身
def self.setup
stub_request(...)
end
但它也不起作用。
当我使用 FlexMock 时会发生类似的事情而不是 WebMock。似乎是一个范围问题,但我无法弄清楚如何解决它。想法?
最佳答案
使用 FakeWeb你可以这样做:
在*test/test_helper.rb*
require 'fakeweb'
class ActiveSupport::TestCase
def setup
# FakeWeb global setup
FakeWeb.allow_net_connect = false # force an error if there are a net connection to other than the FakeWeb URIs
FakeWeb.register_uri(:get,
"https://api.twitter.com/1/users/show.json?screen_name=digiberber",
:body => "",
:content_type => "application/json")
end
def teardown
FakeWeb.allow_net_connect = true
FakeWeb.clean_registry # Clear all registered uris
end
end
有了这个,您可以从任何测试用例调用已注册的假网站。
关于ruby-on-rails - 如何使用 Test::Unit 在全局 stub http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6604963/