如何使用 Test::Unit 全局存根 http 请求?
如何在全局范围内存根 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 时,会发生类似的情况。似乎是范围问题,但我不知道如何解决它。有想法吗?
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 instead of WebMock. Seems to be a scope problem, but I can't figure out how to go around it. Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 FakeWeb 你可以做这样的事情:
在 *test/test_helper.rb* 中
,你可以调用从任何测试用例到注册的 fakeweb。
Using FakeWeb you could do something like this:
In *test/test_helper.rb*
With this, you can call to the registered fakeweb from any testcase.
这篇文章介绍了不同的设置方法( ) 和teardown() 导致我只是
没有想到将其声明为实例方法。 :P
This post on different ways to setup() and teardown() led me to just do
hadn't thought of declaring it as an instance method. :P
capybara 驱动程序 Akephalos 确实支持存根 http 调用。他们称之为过滤器。
http://oinopa.com/akephalos/filters.html
http://github.com/Nerian/akephalos
The capybara driver Akephalos does support stubbing http calls. They call it filters.
http://oinopa.com/akephalos/filters.html
http://github.com/Nerian/akephalos