开发者

Stubbing tests when using Ruby Mechanize

I've been trying to use Mocha to do some stubbing for tests on code using Mechanize. Here is an example method:

  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开发者_Python百科 => 'ctl00$pageContent$searchButton'))
    result.body.downcase.include?(subject_area.downcase) ? result : false
  end

So the get_page method will return a Mechanize::Page with the html parsed and all that good stuff. I'd love it if someone knew a way to take that object and do something like a serialization of it (however, serialize did not work due to one of the sub modules of Mechanize::Page not understanding how to do a dump from Marshalling the object). What I've been having to do, obviously due to my lack in understanding of stubbing, is:

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

The above code is a work-in-progress, because as I was doing it I realized there HAS to be a better way and hopefully one of you smart guys out there has already done this type of thing. I don't want to have to stub out every bit of functionality. Ideally, I'd like to be able to create a Mechanize::Page object with html (since I'll know what the html will be on these pages... and that would be a good stub I think). None the less, I could not figure out how to instantiate a Mechanize::Page with html.

Could anyone guide me in a better direction to testing a method like lookup_course that uses lots of pieces of functionality. Maybe I should break up the logic in my code to make this better (if so, how would you suggest?)

Thank you for your time,

Michael


You could take a look at this Stakoverflow questions which suggests using Fakeweb. Another one worth checking out is Webmock.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜