![](/img/trans.png)
[英]How can I test (with RSpec) that an HTTP request is send in Rails (as part of an unit test)?
[英]How do I stub an http request globally with Test::Unit?
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 => {})
這個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 時,也會發生類似的情況。 似乎是一個 scope 問題,但我不知道如何圍繞它 go。 想法?
使用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。
這篇關於 setup() 和 teardown() 不同方法的帖子讓我做了
class ActiveSupport::TestCase
def setup
stub_request(...)
end
end
沒想到將其聲明為實例方法。 :P
capybara 驅動程序 Akephalos 確實支持存根 http 調用。 他們稱之為過濾器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.