我写了一个小程序,使用 Mechanize 来遍历一个站点。
我想为它编写测试,但不希望它在我每次运行测试时实际登录网站。我想模拟互联网,这样当它进入某个站点时,它只会返回存储的结果。
这是一个小例子,假设我的代码的目的是从谷歌主页中提取链接,所以我编写了一个测试来确保我的代码找到的第一个链接有文本“图片”。我可能会写这样的东西:
require 'rubygems'
require 'mechanize'
require 'test/unit'
def my_code_to_find_links
google = WWW::Mechanize.new.get('http://www.google.com')
# ...
# some code to figure out which links it wants
# ...
google.links
end
class TestGoogle < Test::Unit::TestCase
def test_first_link_is_images
assert_equal 'Images' , my_code_to_find_links.first.text
end
end
如何模拟 google.com 以便我可以测试 my_code_to_find_links 而无需实际访问互联网的所有开销?
谢谢-乔什