ruby-on-rails - 如何使用 Test::Unit 在全局 stub http 请求?

标签 ruby-on-rails testing mocking twitter testunit

我如何在全局范围内 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/

相关文章:

java - 模拟内部状态

ruby-on-rails - 瘦服务器 QUERY_STRING 比 (1024 * 10) 允许的长度长

ruby-on-rails - 您如何限制对某个网页的访问?

ruby-on-rails - 夹具关联在邮件测试中失败

java - Mockito.when then根据输入参数返回

java - 模棱两可的 Mockito - 预期 0 个匹配器,记录 1 个(InvalidUseOfMatchersException)

ruby-on-rails - 在 Rails 4 中使用强参数值白名单

ruby-on-rails - User Helper Method - 抓取ID与当前用户ID不匹配的用户

testing - 如何通过滚动测试 AngularJS 指令

rspec - 用法拉第和 Rspec 打桩