使用FakeWeb进行机械化

Aut*_*act 1 ruby ruby-on-rails mechanize

我正在使用Mechanize从页面中提取链接.为了简化开发,我使用fakeweb进行超高速响应,以减少等待和烦扰每个代码运行.

tags_url = "http://website.com/tags/"
FakeWeb.register_uri(:get, tags_url, :body => "tags.txt")

agent = WWW::Mechanize.new
page = agent.get(tags_url)
page.links.each do |link|
   puts link.text.strip
end
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,它说:

nokogiri_test.rb:33: undefined method `links' for #<WWW::Mechanize::File:0x9a886e0> (NoMethodError)
Run Code Online (Sandbox Code Playgroud)

检查页面对象的类后

puts page.class # => File
Run Code Online (Sandbox Code Playgroud)

如果我没有伪造出tags_url,它就起作用,因为页面类现在是Page

puts page.class # => Page
Run Code Online (Sandbox Code Playgroud)

那么,如何使用机械化的fakeweb来返回Page而不是File对象呢?

Ste*_*ham 7

使用FakeWeb重播预取的HTTP请求:

tags_url = "http://website.com/tags/"
request  = `curl -is #{tags_url}`
FakeWeb.register_uri(:get, tags_url, :response => request)

agent = WWW::Mechanize.new
page = agent.get(tags_url)
page.links.each do |link|
   puts link.text.strip
end
Run Code Online (Sandbox Code Playgroud)

使用-i标志调用curl将在响应中包含标头.


Fel*_*ima 5

您可以轻松修复添加:content_type => "text/html"您的FakeWeb.register_uri通话选项