如何在全局范围内存根一个 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存根在 TestCase 子类的 setup() 块中工作,例如
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 时,也会发生类似的情况。似乎是一个范围问题,但我不知道如何解决它。想法?