开发者

How do I stub an http request globally with Test::Unit?

开发者 https://www.devze.com 2023-03-18 08:44 出处:网络
How do I stub an http request, like this one to the twitter api below, on a global scope so it\'s valid for all tests in a Test::Unit suite?

How do I stub an http request, like this one to the twitter api below, on a global scope so it's valid for all tests in a Test::Unit suite?

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 => {})

This WebMock stub works within a TestCase subclass's setup() block, like

class MyTest < ActiveSupport::TestCase       
  setup do
    stub_request(...)...
  end
end

But doesn't get recognized if I put it within a global setup in TestCase itself:

require 'webmock/test_unit'
class ActiveSupport::TestCase  
  setup do
    stub_request(...)
  end
end

Which gives me the error:

NoMethodError: undefined method `stub_request' for ActiveSupport::TestCase:Class

I've also tried by patching the method def itself

def self.setup
  stub_request(...)
end

but it doesn't work either.

Something similar happens when I use FlexMock ins开发者_运维技巧tead of WebMock. Seems to be a scope problem, but I can't figure out how to go around it. Ideas?


Using FakeWeb you could do something like this:

In *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

With this, you can call to the registered fakeweb from any testcase.


This post on different ways to setup() and teardown() led me to just do

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

hadn't thought of declaring it as an instance method. :P


The capybara driver Akephalos does support stubbing http calls. They call it filters.

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

http://github.com/Nerian/akephalos

0

精彩评论

暂无评论...
验证码 换一张
取 消