【发布时间】:2011-02-21 03:41:50
【问题描述】:
我一直在尝试使用 Mocha 对使用 Mechanize 的代码进行一些存根测试。这是一个示例方法:
def lookup_course subject_area = nil, course = nil, quarter = nil, year = nil
raise ArgumentError, "Subject Area can not be nil" if (subject_area.nil? || subject_area.empty?)
page = get_page FIND_BASIC_COURSES
raise ArgumentError, "Invalid Subject Area" unless page.body.include?(subject_area.upcase)
form = page.form_with(:action => 'BasicFindCourses.aspx')
if !quarter.nil? && !quarter.empty? && QUARTERS.has_key?(quarter.downcase) && year.is_a?(Integer)
form['ctl00$pageContent$quarterDropDown'] = "#{Time.now.year}#{QUARTERS[quarter]}"
puts form['ctl00$pageContent$quarterDropDown']
end
form['ctl00$pageContent$subjectAreaDropDown'] = subject_area
form['ctl00$pageContent$courseNumberTextBox'] = course if (!course.nil? && !course.empty?)
result = form.submit(form.button_with(:name => 'ctl00$pageContent$searchButton'))
result.body.downcase.include?(subject_area.downcase) ? result : false
end
所以 get_page 方法将返回一个 Mechanize::Page ,其中包含已解析的 html 和所有这些好东西。如果有人知道如何获取该对象并对其进行序列化之类的操作,我会很高兴(但是,由于 Mechanize::Page 的子模块之一不了解如何从 Marshalling 进行转储,序列化不起作用物体)。显然,由于我对存根缺乏了解,我一直不得不做的是:
should "return a mechanize page with valid course subject" do
Mechanize::Page.stubs(:body).returns(FIND_COURSE_HTML)
Mechanize::Page.stubs(:form_with).returns(message = {})
Mechanize::Form.stubs(:submit).returns(true)
assert_equal Mechanize::Page, @access.lookup_course("CMPSC").class
end
上面的代码是一个正在进行的工作,因为当我这样做时,我意识到必须有更好的方法,希望你们中的一个聪明人已经做过这种事情。我不想删除所有功能。理想情况下,我希望能够使用 html 创建一个 Mechanize::Page 对象(因为我会知道这些页面上的 html 是什么......我认为这将是一个很好的存根)。尽管如此,我还是不知道如何用 html 实例化 Mechanize::Page。
谁能指导我更好地测试像lookup_course这样使用大量功能的方法。也许我应该分解我的代码中的逻辑以使其更好(如果是这样,你会如何建议?)
感谢您的宝贵时间,
迈克尔
【问题讨论】:
-
我用来规避 stubing Mechanize 本身的混乱的一个解决方案是围绕使用 Mechanize 设计一个更精简的界面...我创建了自己的 get 和 post 方法来包装 Mechanize get/post,这样我就可以尽可能地将我的代码与 Mechanize 分离。仍然有兴趣看看是否有其他方法可以测试 Mechanize for Ruby...不过感谢您的观看。
标签: ruby screen-scraping mechanize