Capping Tests Using Ruby Mechanize
I am trying to use Mocha to do some steps to test code using Mechanize. Here's a sample 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 => 'ctl00$pageContent$searchButton'))
result.body.downcase.include?(subject_area.downcase) ? result : false
end
So the get_page method will return Mechanize :: Page with the rendered html and all that good stuff. I would love it if someone knew a way to take this object and do something like serializing it (however, serialization didn't work due to one of the Mechanize :: Page submodules not understanding how to dump a Marshalling object). What I had to do, obviously due to my lack of understanding of stubbing, is this:
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 incomplete because the way I did it I figured out there must be a better way and hopefully one of you smart guys has already done it. I don't want all functionality to be drowned out. Ideally, I would like to create a Mechanize :: Page object with html (since I will know what the html page will be in those pages ... and that would be a good stub I think). However, I couldn't figure out how to instantiate Mechanize :: Page with html.
Can anyone please direct me in a better direction for testing a method like lookup_course that uses a lot of functionality. Maybe I should break down the logic in my code to do it better (if so, how would you suggest?)
Thank you for your time,
Michael
a source to share