3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Mechanize + WebMockでちょっとハマった

Posted at

Mechanize::FileMechanize::Page

クローラー作ったりしてるんですが、RSpecでテストする時に

before(:each) do
  @agent = Mechanize.new
  stub_request(:get, EXAMPLE_URL).
    to_return(:status => 200, :body => EXAMPLE_BODY, :headers => {})
  @agent.get(EXAMPLE_URL)
end

とかしてたんですが、何故かundefined method 'links' for #<Mechanize::File:...とか言われてしまった訳です。

調べてみたところ、Mechanizeは読み込むコンテンツの種類が分からなかった場合はMechanize::PageではなくMechanize::Fileとして読み込むため、@agent.page.links等が使えなくなるみたいです。

という訳で、ちゃんとヘッダー部分で指定しましょう。

before(:each) do
  @agent = Mechanize.new
  stub_request(:get, EXAMPLE_URL).
    to_return(:status => 200, :body => EXAMPLE_BODY, :headers => {content_type: 'text/html'})
  @agent.get(EXAMPLE_URL)
end

さんこう

ruby on rails - How do I convert from a Mechanize::File object to a Mechanize::Page object? - Stack Overflow

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?