4

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

4

3 回答 3

2

使用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

有了这个,您可以从任何测试用例调用已注册的 fakeweb。

于 2011-07-19T10:06:13.620 回答
1

这篇关于 setup() 和 teardown() 不同方法的帖子让我做了

class ActiveSupport::TestCase  
  def setup
    stub_request(...)
  end
end

没想到将其声明为实例方法。:P

于 2011-07-07T20:39:21.540 回答
0

capybara 驱动程序 Akephalos 确实支持存根 http 调用。他们称之为过滤器。

http://oinopa.com/akephalos/filters.html

http://github.com/Nerian/akephalos

于 2011-07-19T13:14:42.097 回答