2011-07-07 30 views
4

如何在全局作用域上存儲一個http請求,就像下面這個twitter api一樣,所以它對於Test :: Unit套件中的所有測試都是有效的?如何使用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 => {}) 

一個TestCase子類的設置()塊內的這WebMock存根作品,如

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

但沒有得到認可,如果我把它放在測試用例自身的全局設置中:

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時會發生類似的情況。似乎是一個範圍問題,但我不知道如何去解決它。想法?

+0

不好意思,剛纔回答,但錯過了,您使用測試::單位。無論如何,看看FakeWeb。 https://github.com/chrisk/fakeweb – d11wtq

+0

不會fakeweb有相同的問題? register_uri()與webmock的stub_request()非常相似,我也需要全局運行它 – oliverbarnes

+0

也許你可以將HTTP請求抽象成類或模塊方法,然後你可以輕鬆地模擬或存根。 –

回答

1

This post不同的方式來設置()和拆卸()導致我只是做

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

沒想到它聲明爲實例方法。 :P

2

使用FakeWeb你可以做這樣的事情:

在*測試/ 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。