Testing loop using rspec

63 views
Skip to first unread message

Pradeep Achuthan

unread,
Nov 6, 2014, 2:08:06 PM11/6/14
to rs...@googlegroups.com

I have a ruby method written and I need to test it. Below is my method.

    def iterate_each_doc
      count=1
      arr_of_doc = []
      max_offset = 700
      loop do
        begin
          feed_url = "http://www.example.com?q=&page=#{count}"
          json_doc = JSON.parse(page)
          jsons_rec = get_json_rec(json_doc)
   
          if jsons_rec.size > 0
            arr_of_doc += jsons_rec
          end
   
          count += 1
          break if json_doc["list"].empty? && offset > json_doc["lastPage"]
   
        rescue
          catch exception
        end
      end
      arr_of_doc
    end

I tested the return value of the method as below

    it "should fetch from json document and return an array of videos containing only full episodes" do
          stub_request(:get, url).to_return(status: 200, :body => File.read(File.join(json_saved_pages_path, 'sample.json')))
          result = subject.iterate_each_doc
          result.should_not be_empty
          result.size == 3
     end

But I need to make sure that the loop executes without any fail and
breaks only till it satisfies the condition

i.e.

    if json_doc["list"].empty? && offset > json_doc["lastPage"]

This condition will satisfy till lastpage of the json doc is 700. But
in my rspec I cannot allow to execute the loop everytime till the
condition. So what would be the best way to achieve this. Please help.


Myron Marston

unread,
Dec 9, 2014, 11:38:58 AM12/9/14
to rs...@googlegroups.com
Achu,

The normal way people deal with this is to separate the fetching of a specific real page from the logic that parses it.  The condition you are interested in testing is part of the logic that parses the page.  By making it a separate object that does only the parsing, you can test it with many example JSON documents of various sizes and various contents.  You can tightly control what the example data is.

HTH,
Myron
Reply all
Reply to author
Forward
0 new messages