【问题标题】:How do I stub an http request globally with Test::Unit?如何使用 Test::Unit 全局存根 http 请求?
【发布时间】:2011-07-07 01:45:06
【问题描述】:

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

【问题讨论】:

  • 抱歉,刚刚回答但错过了您正在使用 Test::Unit。无论如何,看看 FakeWeb。 github.com/chrisk/fakeweb
  • fakeweb 不会有同样的问题吗? register_uri() 与 webmock 的 stub_request() 非常相似,我也需要全局运行它
  • 也许您可以将 HTTP 请求抽象为一个类或模块方法,然后您可以轻松地模拟或存根。
  • @Wizard of Ogz,实际上那是我最初的方法——在全局 setup() 下使用 flexmock 将 twitter gem 的 Twitter.user() 存根。但是 flexmock() 也没有得到认可:P。我认为在这两种方法中我只是在错误的地方存根,但无法找出正确的地方
  • ...我的意思是我只是在错误的地方添加了存根调用,在该位置无法识别模拟库。我无法弄清楚正确的位置在哪里,或者如何强制在其中包含那些存根/模拟方法。例如,尝试了 FlexMock.flexmock(),但 Flexmock 模块不存在,尽管它是必需的(尝试包含(),但也没有运气)

标签: ruby-on-rails testing mocking twitter testunit


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    This post 关于 setup() 和 teardown() 的不同方法让我这样做

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

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

    【讨论】:

      【解决方案3】:

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

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

      http://github.com/Nerian/akephalos

      【讨论】:

        猜你喜欢
        • 2016-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-12
        • 2021-09-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多