Applying SitePrism.Vcr to stub API calls triggered by events in SitePrism sections

Posted: Dec 10, 2014

Recently I have had to stub API responses in our tests when an user uses pagination. We have the pagination similar to the pagination of Facebook: you scroll down and you receive new items in the list. It was challenging, because SitePrism.Vcr only allows you to link VCR cassettes with elements and pages. In our case we needed a possibility to link VCR cassettes with a section (actually we needed to apply VCR cassettes on a scroll event within a section). I started thinking about adding new functionality into SitePrism.Vcr to have such possibility. I was thinking about:

class ProductsPage < SitePrism::Page
  section_with_vcr \
    :details,
    DetailsSection,
    '#products_list' do
      fixtures ['cars']
    end
end

But, after reviewing the code of SitePrism.Vcr, I realized how it is easy to achieve that without any modifications in the gem. The gem has SPV::Applier class which manages VCR cassettes within elements and pages. For each element and page that we apply VCR for we have own instance of this class. As a result, we had everything what we needed to achieve our goal:

class ListSection < SitePrism::Section
  # elements here

  def initialize(parent, element)
    super

    @applier = SPV::Applier.new(self)
  end

  def show_more
    @applier.shift_event{
      self.scroll_down
    }.apply_vcr do
      fixtures ["storage/more_storage"]

      waiter { self.wait_until_loading_indicator_invisible }
    end
  end
end

We got what we needed without any changes in SitePrism.Vcr with the code listed above.

It was another prove for us that Single Responsibility Principle works well.

Create flexible code and you will receive more features than you code.