4

Test :: Unitスイートのすべてのテストで有効になるように、グローバルスコープでこのようなhttpリクエストをグローバルスコープでスタブするにはどうすればよいですか?

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

しかし、それも機能しません。

WebMockの代わりにFlexMockを使用すると、同様のことが起こります。スコープの問題のようですが、回避方法がわかりません。アイデア?

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

カピバラドライバーのAkephalosは、http呼び出しのスタブをサポートしています。彼らはそれをフィルターと呼んでいます。

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

http://github.com/Nerian/akephalos

于 2011-07-19T13:14:42.097 に答える